【发布时间】:2019-04-21 08:15:06
【问题描述】:
我通过 children 属性作为函数创建了以下渲染道具组件:
export class GenericAbstractLoader extends React.Component<IGenericAbstractLoaderRenderProps, any> {
constructor(props: IGenericAbstractLoaderRenderProps) {
super(props);
}
public render() {
return this.props.isLoading ? (
<div className="generic-abstract-loader-wrapper">
<div className="generic-abstract-loader">
<img src={loader} />
</div>
{this.props.children(this.props)}
</div>
) : (
this.props.children(this.props)
);
}
}
如果isLoading 为假,它实际上只是渲染包装的组件,或者如果道具为真,则添加一层加载。
它“非常完美”地工作。
我确实从另一个组件以这种方式调用它:
public render() {
return (
<div>
<button onClick={this.justDisable}>JUST SET FALSE TO STATE</button>
<br />
<button onClick={this.enableDisable}>Disable/Enable Elements</button>
<br />
<GenericAbstractLoader customProp="custom prop" isLoading={this.state.shouldDisable}>
{props => <HomeTestForm {...props} />}
</GenericAbstractLoader>
</div>
);
}
如您所见,包装的组件是一个简单的HomeTestForm,它只包含一个输入文本:
export class HomeTestForm extends React.Component<IGenericAbstractLoaderHOCProps, any> {
constructor(props: IGenericAbstractLoaderHOCProps) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = { value: 'Initial Value' };
}
public render() {
return (
<div>
<input type="text" value={this.state.value} onChange={this.handleChange} />
</div>
);
}
public handleChange(event: any) {
this.setState({ value: event.target.value });
}
}
我的问题是,当我切换 isLoading 属性时,包装组件不会保留状态,所以如果我更改内部文本字段的值,添加加载层时,以及删除它时,该值不被采用,因此输入字段仍然使用初始值呈现。
使用渲染道具创建持久包装组件的正确方法是什么?
【问题讨论】:
-
我说的不是应用程序状态,而是简单的组件状态。我不想为此使用 redux。我只需要一种方法来存储传入的包装组件的当前状态(
this.state让我们说理解)。
标签: javascript reactjs