父组件给子组件传值
思路:把需要传递的值获取,并放入state中,并把state中的值通过props传递给子组件;子组件在根据父组件传递来的值进行处理。
// 首先创建父组件
class ParentCom extends React.Component{
constructor(props){
super(props)
this.state=({
content:'给子传input',
zi_content:'' // 这个是需要传递的值
})
}
// 父组件通过此方法,把需要传递的值,放入state中。
giveValue = (e) =>{
let value = document.getElementById("fu_input").value;
this.setState({
zi_content : value
});
}
render(){
return(
<div>
<Button onClick={this.giveValue}>给子传值</Button>
<Input id="fu_input" defaultValue={this.state.content}></Input>
{/* 把需要传递的值,传递给子组件 */}
<ChildCom zi_content = {this.state.zi_content}/>
</div>
)
}
}
// 创建子组件
class ChildCom extends React.Component{
constructor(props){
super(props)
}
render(){
let val = '';
if(this.props.zi_content){
// 获取props中,父组件传递过来的值
val = this.props.zi_content
}
return(
<div>
<div>我是子</div>
<Input defaultValue={val} value={val}></Input>
</div>
)
}
}
ReactDOM.render(
<ParentCom />,
document.getElementById('root')
)
子组件给父组件传值
思路:由于子组件并不能直接处理父组件的状态,但是我们可以通过父组件的方法更改父组件的状态。
// 创建父组件
class FuCom extends React.Component{
constructor(props){
super(props)
this.state=({
zi_value:""
})
}
// 父组件定义方法 可以修改父组件的值,把这个方法传递给子组件
changeData = (msg,e) =>{
this.setState({
zi_value:msg
})
}
render(){
return(
<div>
子组件传来的值:
<span>{this.state.zi_value}</span>
{/*把修改父组件数据的函数传递给子组件*/}
<ZiCom changeData={this.changeData}/>
</div>
)
}
}
// 创建子组件
class ZiCom extends React.Component{
constructor(props){
super(props)
this.state=({
input_val:"子组件的初始内容"
})
}
// 子组件接收 从父组件传来的 修改父组件值的方法 传递参数 修改父组件的值
sendData = (e) =>{
let val = document.getElementById("inputId").value;
this.props.changeData(val)
}
render(){
return(
<div>
<Input type="text" id="inputId" defaultValue={this.state.input_val} ></Input>
<Button onClick={this.sendData}>给父传值</Button>
<Button onClick={(e)=>{this.props.changeData('Hello world',e)}}>直接通过props 函数</Button>
{/* <Button onClick={function(e){this.changeData('dd',e)}.bind(this)}>不使用es6绑定函数</Button> */}
</div>
)
}
}
ReactDOM.render(
<FuCom />,
document.querySelector('#root2')
)