【发布时间】:2021-05-05 18:31:39
【问题描述】:
<CheckboxGroup name="fruits" value={fruits} onChange={this.setFruits}>
{(cb) => (
<>
<label>
<Checkbox value="apple" /> Apple
</label>
<label>
<Checkbox value="orange" /> Orange
</label>
<label>
<Checkbox value="watermelon" /> Watermelon
</label>
</>
)}
</CheckboxGroup>
这里是父组件。我想将名称、值和 onChange 传递给孩子们。
class CheckboxGroup extends React.Component {
constructor(props){
super(props);
this.state = {
value: this.props.value,
name: this.props.name
}
}
render() {
const children = React.Children.map(this.props.children(), child => {
return React.cloneElement(child);
});
return(
<>
{children}
</>
)
}
}
class Checkbox extends React.Component {
constructor(props){
super(props);
}
render() {
console.log(this.props);
return (
<>
<input type="checkbox" value="" name="" />
</>
);
}
}
如何在孩子中获得父母的道具?我使用的是this.props.children() 而不是this.props.children。从父母那里,我尝试过 React.cloneElement(child, {this.props}) 但不起作用。
【问题讨论】:
-
是否有特定原因需要使用 React.cloneElement?您的示例似乎不需要此 API 提供的任何特殊功能。
-
嘿@LyndenNoye 我想使用cloneElement,这样我就可以使用''' '''。只需要子组件中的名称和值。有没有其他办法?
标签: reactjs