理論性的知識咋們後期加,主要實現下最基本的父子互傳。
直接附代碼
父組件
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>
);
}
}