* 在react中,數據是單向流動的(即從dom樹中自上向下流動)
1.父子通信
在父組件通過注冊屬性的形式向子組件傳遞值,子組件通過this.props接受來之父組件的屬性及屬性值
~~~
import React from 'react'
import Child from './Child.js'
export default class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
value: ''
}
}
handleChange(e) {
var value = e.target.value;
this.setState({ value: value })
}
render() {
const { value } = this.state
return (
<div>
父親說:<input value={value} onChange={this.handleChange.bind(this)} />
//使用val屬性傳參
<Child val={value} />
</div>
)
}
}
~~~
~~~
import React from 'react'
export default class Child extends React.Component{
render() {
const { val } = this.props;
return (
<div>
<p>父親對兒子說:{val}</p>
</div>
)
}
}
~~~
2.子父通信
子組件通過調用父組件傳遞的方法向父組件傳值
~~~
import React from 'react'
import Child from './Child.js'
export default class Swip extends React.Component {
constructor(props) {
super(props)
this.state = {
value: '',
childSaid: ''
}
}
handleChange(e) {
var value = e.target.value;
this.setState({ value: value })
}
childSay(val) {
this.setState({ childSaid: val })
}
render() {
const { value, childSaid } = this.state
return (
<div>
父親說:<input value={value} onChange={this.handleChange.bind(this)} />
<Child say={this.childSay.bind(this)} val={value} />
<p>兒子對父親說:{childSaid}</p>
</div>
)
}
}
~~~
~~~
import React from 'react'
export default class Child extends React.Component {
constructor(props) {
super(props)
this.state = {
value: ''
}
}
handleChange(e) {
const { say } = this.props;
var value = e.target.value;
this.setState({ value: value });
// 調用父組件的方法
say(value);
}
render() {
const { val } = this.props;
const { value } = this.state;
return (
<div>
<p>父親對兒子說:{val}</p>
兒子說:<input value={value} onChange={this.handleChange.bind(this)} />
</div>
)
}
}
~~~