我正在实现一个嵌套组件,我的所有组件都需要有 variable 属性,现在我有:
<Parent variable="myVariable">
<Child1 variable="myVariable" />
<Child2 variable="myVariable" />
</Parent>
但我不想将 prop 直接传递给每个组件,我需要这样的东西:
<Parent variable="myVariable">
<Child1 />
<Child2 />
</Parent>
我需要从 Child1 和 Child2 访问variable prop。
最佳答案
有两种解决方案可以做到这一点。在父组件中使用 React.createContext 或 React.cloneElement。
I highly recommend using React.createContext in React 16.3+ since this is exactly what React Context is meant for. Its also especially helpful if you have flow to keep
prop
type checking working properly.Note in React 16.6 its even easier to use context by using contextType.
https://reactjs.org/docs/context.html
(或使用 create-react-context https://github.com/jamiebuilds/create-react-context )如果您不是最新的。
// parentFile.js
import * as React from 'react';
export const MyContext = React.createContext(); // React.createContext accepts a defaultValue as the first param
type Props = {
variable: string,
children: React.Node
};
class Parent extends React.Component<Props> {
render() {
return (
<MyContext.Provider value={{ variable: this.props.variable }}>
{this.props.children}
</MyContext.Provider>
);
}
}
class Child1 extends Component<{}> {
static contextType = MyContext;
render() {
return (<div>{this.context.variable}</div>);
}
}
// IF you have a child in a different file make sure you import the correct consumer
// child2.js
import * as React from 'react';
import { MyContext } from './parentFile';
class Child2 extends Component<{}> {
static contextType = MyContext;
render() {
return (<span>{this.context.variable}</span>);
}
}
React.createContext 在这里大放异彩,您可以在其中处理嵌套组件
// Example of using Parent and Child
import * as React from 'react';
class SomeComponent extends React.Component<{}> {
render() {
<Parent variable="test">
<Child1 />
{ /* Previously you couldn't use
React.cloneElement to handle the nested case */ }
<SomeOtherComp>
<Child2 />
</SomeOtherComp>
</Parent>
}
}
This is a quick example of how to do this without React Context and using React.cloneElement
import * as React from 'react';
class Parent extends Component {
render() {
const { children, props } = this.props;
return (
React.Children.map(children, child =>
React.cloneElement(child, {...props})
)
);
}
}
关于javascript - 将 Prop 传递给它的所有 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49726000/