理论性的知识咋们后期加,主要实现下最基本的父子互传。
直接附代码
父组件
import React, { Component } from 'react';
import Child from '../children';
export default class index extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
visible: true
};
}
handelClick() {
console.log(this);
}
fn(data) {
// console.log(data,'data');
this.setState({
count: data
}, () => {
console.log(this.state.count,'父组件');
});
}
render() {
return (
<div style={{background:'green'}}>
{this.state.count}
父组件
<Child count={this.state.count} pfn={this.fn.bind(this)}></Child>
<button onClick={this.handelClick.bind(this)}>点击</button>
</div>
);
}
}
子组件
import React, { Component } from 'react';
export default class index extends Component {
constructor(props) {
super(props);
this.state = {
count: props.count
};
}
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.count !== prevState.count) {
return {
count: nextProps.count
};
}
return null;
}
handleC(text) {
// console.log(text);
this.props.pfn(text);
}
render() {
return (
<div style={{border: 'solid 1px #ccc', margin: '0 20px'}}>
这是子组件
{this.state.count}
<button style={{width:'200px', height:'100px'}} onClick={this.handleC.bind(this, 2)}>点击向父组件传递</button>
</div>
);
}
}