在我的应用程序中,我有几个表单字段组件,它们的行为方式都相同,但看起来略有不同。我希望能够使用单个表单域组件的状态和类方法,同时提供某种替代渲染方法,以便我可以即时自定义此元素的外观。我知道我可以包装 child ,然后在组件中使用 props.children
。但我希望以某种方式重新使用组件方法:
class Parent extends React.Component {
render() {
<div className="parent">
<ChildFormField
renderAlternate={self => {
return (
<div className="child--alternate">
<input onChange={self.doThing} />
</div>
);
}}
/>
</div>
}
}
// And the child component look something like...
class ChildFormField extends React.Component {
state = {
value: null
}
doThing = value => {
return this.setState({ value });
}
render() {
if (this.props.renderAlternate !== undefined) {
return this.props.renderAlternate();
}
// standard return
return <div />;
}
}
除了基本用法之外,我对 React 还比较陌生。是否有推荐的方法来实现此功能?
最佳答案
您的renderAlternate
函数需要一个参数self
。所以调用的时候需要传递this
return this.props.renderAlternate(this);
参见 https://codesandbox.io/s/w759j6pl6k作为您的代码示例。
关于javascript - 为 React Component 提供替代渲染方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53709856/