組件間通信:
- React中,數據是從上向下流動的,也就是一個父組件可以把它的 state/props通過props傳遞給它的子組件,但是子組件,不能修改props,如果組件需要修改父組件中的數據,則可以通過回調的方法來完成,
- 說白了就是子組件想要修改父組件的值,就是在父組件調用子組件的地方,傳遞一個方法,改方法首先在父組件中定義,子組件通過props的獲取到父組件傳遞的方法,子組件就可以調用該方法,也可以利用這個回調傳值
定義父組件app.js
在父組件中定義一個方法傳遞給子組件
import React, { Component } from "react";
import Home from "./components/Home.jsx";class App extends Component {
constructor() {
super();
this.state = {
value: "父組件的值",
};
}
render() {
return (
<div>
{this.state.value}
<Home changevalue={this.changevalue}></Home>
</div>
);
}
changevalue = (value) => {
console.log(value);
this.setState({
value,
});
};
}
export default App;
定義子組件child
子組件中從props里獲取到父組件傳遞過來的方法,調用即可,使用的使用一定要注意this問題,這里涉及到給父組件傳值(回調里),實際開發中比這要難...,大致思路就是這樣
import React, { Component } from "react";
export default class home extends Component {
constructor(props) {
super(props);this.state = {
text: "子組件要傳給父組件的值",
};
}
render() {
return (
<div>
<button onClick={this.toparent}>點擊給父組件</button>
</div>
);
}
toparent = () => {
const { changevalue } = this.props;
changevalue(this.state.text) //調用父組件的方法傳值
}
}
