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}} />
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
子组件代码如下:
复制代码componentWillReceiveProps(nextProps) {
const { data } = this.state
const newdata = nextProps.data.toString()
if (data.toString() !== newdata) {
this.setState({
data: nextProps.data,
})
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
ps:react的componentWillReceiveProps周期是存在期用改变的props来判断更新自身state。
上面是“react如何实现父组件传值子组件(子组件只负责渲染)”的全面内容,想了解更多关于 reactjs 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_2756.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!