避免将 props 传递给多个组件的一种方法是使用 reacts context api。
这允许我们从MyProvider 组件向下访问 100 个子组件的状态,而无需手动将 props 向下传递到 100 个子组件。
import React, { Component } from "react";
import { render } from "react-dom";
// first make a new context
const MyContext = React.createContext();
// Then Create a provider Component
class MyProvider extends Component {
state = {
name: "Junie",
age: 21
};
render() {
return (
<MyContext.Provider
value={{
state: this.state,
increment: () => this.setState({ age: this.state.age + 1 })
}}
>
{this.props.children}
</MyContext.Provider>
);
}
}
const App = () => {
return (
<MyProvider>
<div>
<p>Hello I'm the App </p>
<Child />
</div>
</MyProvider>
);
};
const Child = props => {
return (
<div>
<Child2 />
</div>
);
};
class Child2 extends Component {
render() {
return (
<div>
<p> Im Child 2 </p>
<MyContext.Consumer>
{context => (
<div>
{" "}
<p>
{" "}
Inside the context consumer: {context.state.name}{" "}
{context.state.age}
</p>{" "}
<button onClick={context.increment}>Update Age </button>
</div>
)}
</MyContext.Consumer>
</div>
);
}
}
render(<App />, document.getElementById("root"));
使用context 可能是您正在寻找的。p>
还有另一个实现。
class Parent extends React.Component {
state={childstate:''}
getFromChild = (value) => {
this.setState({childstate:value})
}
render() {
return (
<div>
<Child1 getFromChild={this.getFromChild/>
{this.state.childstate && <div> {this.state.childstate} </div>}
</div>
)
}
}
const Child1 = (props) => <Child2 getFromChild={props.getFromChild}/>
class Child2 extends React.Component {
state={somevalue:10}
sendValue = (value) => this.props.getFromChild(value)
render() {
return (
<div>
<button onClick={() => this.sendValue(this.state.somevalue)} />
</div>
)
}
}
很简单,我们在父级中使用 setter 来获取相应子级的状态。
我们将一个值作为参数并将父状态的状态设置为该值。我已将其命名为 childstate,因此很清楚我们发送给父级的任何值都来自子级。
getFromChild = (value) => this.setState({childstate:value})
将函数作为道具从Child1 传递给Child2
<Child2 getFromChild={props.getFromChild}/>
在Child2 添加 onClick 处理程序以将值从子级发送到Parent
<button onClick={() => this.sendValue(this.state.somevalue)} />