1. 程式人生 > >react 元件傳值 (父傳子)

react 元件傳值 (父傳子)

<script type="text/babel">
//父傳子   子元件獲取父元件資料
var Child = React.createClass({
return(
<div>
<h2>子元件通過屬性傳值</h2>
<div>子元件獲取父元件內容 {this.props.name}</div>
<div>子元件獲取父元件內容{this.props.val}</div>
<div>input   {this.props.inputval}</div>
</div>
)
}
})
var Father = React.createClass({
getInitialState:function(){  //設定預設狀態值
return{
message:"父元件資料",
inputVal:''
}
},
change:function(e){
console.log(e.target.value)
this.setState({
inputVal:e.target.value
})
},
render:function(){
return(
<div>
<h1>父元件</h1>
<input type="text" onChange={this.change}/>
<Child name="ouyang" inputval={this.state.inputVal} val={this.state.message}/>
</div>
)
}
})
ReactDOM.render(<Father/>,document.getElementById('out'))
</script>