react.js - react的state不会自动继续传递吗?
本文介绍了react.js - react的state不会自动继续传递吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
var App = React.createClass({
getInitialState : function () {
return {
value : 'Heading\n=======\n\nSub-heading\n-----------\n \n### Another deeper heading\n \nParagraphs are separated\nby a blank line.\n\nLeave 2 spaces at the end of a line to do a \nline break\n\nText attributes *italic*, **bold**, \n`monospace`, ~~strikethrough~~ .\n\nShopping list:\n\n * apples\n * oranges\n * pears\n\nNumbered list:\n\n 1. apples\n 2. oranges\n 3. pears\n\nThe rain---not the reign---in\nSpain.\n\n *[Herman Fassett](http://freecodecamp.com/hermanfassett)*'
}
},
upDate : function (msg) {
this.setState({
value : msg
})
},
render : function () {
console.log(this.state.value)
return (
<div className="row" style={{marginTop: 30 + "px"}}>
<TextArea value= { this.state.value } upDate = {this.upDate}/>
<Display value = { this.state.value }/>
</div>
)
}
})
var TextArea = React.createClass({
getInitialState : function () {
return {
value : this.props.value
}
},
handleChange : function (e) {
this.props.upDate(e.target.value)
this.setState({
value : e.target.value
})
},
render : function () {
return (
<div className="col-sm-5 col-sm-offset-1">
<textarea ref='mytextArea' className="form-control" rows="27" style= {{resize: "none"}} value={this.state.value} onChange={this.handleChange}></textarea>
</div>
)
}
})
var Display = React.createClass({
getInitialState : function () {
return {
value : this.props.value
}
},
render : function () {
return (
<div className="col-sm-4" style={{marginLeft: 60 + "px"}}>
{this.state.value}
</div>
)
}
})
React.render(<App/>,document.getElementById("container"))
第一次传值是把父组件的状态传递给每个组件,然后子组件的输入被更改,父组件的状态也被更改,不会继续传递给Display组件吗?
解决方案
首先marginTop: 30 + "px"
可以直接写marginTop: "30px"
你把父组件的状态作为字组件的状态,这个方法不建议用,因为react的加载方式决定了,你把父组件的state作为组件的state,只会渲染一次,不管你的父组件的状态变化多少次,子组件的state 还是第一次的值。除非你在子组件里面进行更改子组件的value,用this.setState
这样说你就可以明白了,我们采用react生命周期来解决这个问题
componentWillReceiveProps(nextProps) {
console.log(nextProps)
//主要是写给你看里面 <TextArea value= { this.state.value } upDate = {this.upDate}/>
//所有的属性都在nextProps
//所以这个时候你在调用
this.setState({value:nextProps.value})
}
这样应该就可以了
这篇关于react.js - react的state不会自动继续传递吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文