简单的说一下父传子(属性传值)
1.一般而言,我们用的是ES6中的class类来书写
import React, {Component} from 'react';
class Abc extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
</div>
);
}
}
export default Abc;
2.在父组件中
import React, {Component} from 'react';
import Abc from "../to/abc"; //---<引入子文件
class App extends Component {
constructor(props) {
super(props);
this.state={
aa:"hello react" //--->初始化
}
}
render() {
return (
<div>
<Abc cd={this.state.aa} ac="我是父组件给子组件传的值"> </Abc>
</div>
);
}
}
export default App;
3.在子组件中(abc.js)
import React, {Component} from 'react';
class Abc extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<p>{this.props.ac}</p> //--->我是父组件给子组件传的值
<p>{this.props.cd}</p> //--->hello react
</div>
);
}
}
export default Abc;
子组件给父组件传递值
1.要先在子组件中定义一个方法,通过方法的参数,将值传递给父组件
import React, {Component} from 'react';
class Abc extends Component {
constructor(props) {
super(props);
}
tag(){
this.props.tag1("我是子组件传递给父组件的值");//--->tag1是父组件的变量名
}
render() {
return (
<div>
<p>{this.props.ac}</p>
<p>{this.props.cd}</p>
{/* bind是改变this的指向,也可以用箭头函数改变*/}
<button onClick={this.tag.bind(this)}>点击切换父组件的内容</button>
</div>
);
}
}
export default Abc;
2.在父组件中
import React, {Component} from 'react';
import To from "../to/to";
import List from "../to/list";
import Abc from "../to/abc";
class App extends Component {
constructor(props) {
super(props);
this.state={
aa:"hello react"
}
}
ch(q){
alert(q);//--->q就是子组件传递过来的内容
this.setState({aa:q});//--->在更新当前的aa的内容
}
render() {
return (
<div>
<Abc cd={this.state.aa} ac="我是父组件给子组件传的值"
tag1={this.ch.bind(this)}> </Abc>
</div>
);
}
}
export default App;
兄弟传值
就是把父传子,子传父结合到了一起,通过子组件(定义一个方法,通过方法的参数),将值传递到父组件,在通过父组件(属性传值),传递给另一个子组件
不过后面会有redux,react-redux传值,会方便很多