React组件之间的传值有许多种方式:
- 父组件传值给子组件:父组件可以通过props属性向子组件传递数据或方法,子组件可以通过this.props获取到传递过来的参数。
// 父组件
class Parent extends React.Component {
render() {
const name = "John";
return (
<Child name={name} />
);
}
}
// 子组件
class Child extends React.Component {
render() {
const { name } = this.props;
return (
<div>Hello, {name}</div>
);
}
}
- 子组件传值给父组件:子组件可以通过props属性传递一个回调函数到父组件,父组件在调用子组件时传递一个函数作为参数,子组件可以在需要传递值的地方调用这个回调函数。
// 父组件
class Parent extends React.Component {
handleChildValue = (value) => {
console.log(value); // "Hello, World!"
}
render() {
return (
<Child onValueChange={this.handleChildValue} />
);
}
}
// 子组件
class Child extends React.Component {
handleClick = () => {
const { onValueChange } = this.props;
onValueChange("Hello, World!");
}
render() {
return (
<button onClick={this.handleClick}>Click me</button>
);
}
}
- 兄弟组件之间传递值:使用React的状态提升(State Lifting)将共享状态提升到它们的最近的父组件中,然后再通过props属性向下传递给需要共享的子组件。
// 最近的共同父组件
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
}
handleValueChange = (value) => {
this.setState({ value });
}
render() {
const { value } = this.state;
return (
<div>
<Child1 value={value} onValueChange={this.handleValueChange} />
<Child2 value={value} />
</div>
);
}
}
// 子组件1
class Child1 extends React.Component {
handleChange = (event) => {
const { onValueChange } = this.props;
onValueChange(event.target.value);
}
render() {
const { value } = this.props;
return (
<input value={value} onChange={this.handleChange} />
);
}
}
// 子组件2
function Child2(props) {
const { value } = props;
return (
<div>Value: {value}</div>
);
}