React 組件資料傳遞
React 是一個由 Facebook 所開發的 JavaScript 函式庫,可以讓開發者建立互動式的網頁應用程式。React 的組件資料傳遞是一個重要的概念,它可以讓開發者將資料從父組件傳遞到子組件,並且可以讓子組件回傳資料給父組件。
在 React 中,父組件可以使用 props 來傳遞資料給子組件,而子組件可以使用 state 來回傳資料給父組件。
父組件傳遞資料給子組件
父組件可以使用 props 來傳遞資料給子組件,例如:
class Parent extends React.Component {
render() {
return (
);
}
}
class Child extends React.Component {
render() {
return (
My name is {this.props.name}
My age is {this.props.age}
);
}
}
在上面的程式碼中,父組件 Parent 將 name 和 age 的資料傳遞給子組件 Child,子組件 Child 就可以使用 this.props.name 和 this.props.age 來取得父組件傳遞的資料。
子組件回傳資料給父組件
子組件可以使用 state 來回傳資料給父組件,例如:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
age: 0
};
}
handleChildData = (name, age) => {
this.setState({
name: name,
age: age
});
}
render() {
return (
);
}
}
class Child extends React.Component {
handleClick = () => {
this.props.onChildData('John', 20);
}
render() {
return (
);
}
}
在上面的程式碼中,父組件 Parent 將 handleChildData 的函式傳遞給子組件 Child,子組件 Child 就可以使用 this.props.onChildData 來呼叫父組件傳遞的函式,並且將資料回傳給父組件。