2024年09月26日 建站教程
react如何实现父组件传值子组件,而子组件只负责渲染数据,下面web建站小编给大家详细介绍一下实现代码!
父组件代码如下:
class father extends Component {
constructer(props) {
super(props);
this.state={
a:'1',
b:'2',
data:'',
}
}
getcomposedata() {
const { a, b } = this.state
const data = { a, b }
fetch('/url', {data}).then(res => {
if (res.code === 0) {
this.setState({
data:res.data
})
} else {
message.error(res.errmsg)
}
})
}
render() {
<Children data={this.state.data}} />
}
}
子组件代码如下:
componentWillReceiveProps(nextProps) {
const { data } = this.state
const newdata = nextProps.data.toString()
if (data.toString() !== newdata) {
this.setState({
data: nextProps.data,
})
}
}
ps:react的componentWillReceiveProps周期是存在期用改变的props来判断更新自身state。
本文链接:http://so.lmcjl.com/news/13948/