Dan*_*ori 24 javascript reactjs
我有一个React组件(React v15.5.4),您可以将其他组件传递给:
class CustomForm extends React.Component {
...
render() {
return (
<div>
{this.props.component}
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个使用它的不同组件:
class SomeContainer extends React.Component {
...
render() {
let someObjectVariable = {someProperty: 'someValue'};
return (
<CustomForm
component={<SomeInnerComponent someProp={'someInnerComponentOwnProp'}/>}
object={someObjectVariable}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
一切都很好,但我想将someObjectVariable prop 传递给CustomForm中的子组件(在这种情况下,它将是SomeInnerComponent),因为在实际代码中你可以传递几个组件而不是像示例一样.
请注意,我还需要传递SomeInnerComponent自己的道具.
有没有办法做到这一点?
May*_*kla 15
您可以使用React.cloneElement实现此目的.
像这样:
class CustomForm extends React.Component {
...
render() {
return (
<div>
{React.cloneElement(this.props.component,{ customProps: this.props.object })}
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
工作守则:
class Parent extends React.Component{
render() {
return(
<Child a={1} comp={<GChild/>} />
)
}
}
class Child extends React.Component{
constructor(){
super();
this.state = {b: 1};
this.updateB = this.updateB.bind(this);
}
updateB(){
this.setState(prevState => ({b: prevState.b+1}))
}
render(){
var Comp = this.props.comp;
return (
<div>
{React.cloneElement(Comp, {b: this.state.b})}
<button onClick={this.updateB}>Click to update b</button>
</div>
);
}
}
const GChild = props => <div>{JSON.stringify(props)}</div>;
ReactDOM.render(
<Parent />,
document.getElementById('container')
);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container' />Run Code Online (Sandbox Code Playgroud)
您可以像对SomeInnerComponent.
只需传递命名道具。
里面CustomForm,
render() {
const MyComponent = this.props.component; //stored it in some variable
return (
<div>
<MyComponent customProps = {this.props.object} /> //access object here and passed it or passed individual props
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
编辑 :
您有几种选择来实现您的要求。
class SomeContainer extends React.Component {
...
render() {
let someObjectVariable = {someProperty: 'someValue'};
return (
<CustomForm
component={<SomeInnerComponent propFromParent={someObjectVariable}/>}
object={someObjectVariable}
/>
);
}
Run Code Online (Sandbox Code Playgroud)
}
或者您可以克隆组件道具并应用新道具,如 Mayank 所说。在你的情况下
class CustomForm extends React.Component {
...
render() {
return (
<div>
{React.cloneElement(this.props.component,
{propFromParent:this.props.someObjectVariable})}
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)