渲染函数中的 HOC 与 Wrapper
HOC vs Wrapper in render function
除了"code organizing"之外,这两种方法之间还有什么区别吗?
我有一堆自定义输入元素,例如 TextInput、NumberInput 等
我直接用
const TextInput = (props) => <input type="text" {...props} />
const App = (mainProps) => <div>
<TextInput {...props} errors={['error text']} />
</div>
我有 FormInput 组件,它封装了为任何输入组件呈现的错误消息。
const FormInput = (props) => <div>
// Render input here
<span>{props.errors.join(', ')}</span>
</div>
我看到两种不同的实现方式
1) 高级
const FormInputHOC = (C) => {
const FormInput = (props) => <div>
<C {...props} />
<span>{props.errors.join(', ')}</span>
</div>
}
export default FormInputHOC(TextInput)
2) 包装器
const FormInput = (props) => <div>
{props.children}
<span>{props.errors.join(', ')}</span>
</div>
const TextInput = (props) => <FormInput errors={props.errors}>
<input type="text" {...props} />
</FormInput>
在你的情况下,没有真正的区别,但是当你想对组件状态进行操作时,HOC 允许你编写可以在 this.state
上工作的函数。此状态将是 HOC 包装的组件之一。
示例:
使用 HOC,您可以编写一个 componentWillReceiveProps()
函数,每当组件接收到 props 时,该函数将在组件状态上添加或删除一些数据。您可以在多个组件上使用此 HOC。
除了"code organizing"之外,这两种方法之间还有什么区别吗?
我有一堆自定义输入元素,例如 TextInput、NumberInput 等
我直接用
const TextInput = (props) => <input type="text" {...props} />
const App = (mainProps) => <div>
<TextInput {...props} errors={['error text']} />
</div>
我有 FormInput 组件,它封装了为任何输入组件呈现的错误消息。
const FormInput = (props) => <div>
// Render input here
<span>{props.errors.join(', ')}</span>
</div>
我看到两种不同的实现方式 1) 高级
const FormInputHOC = (C) => {
const FormInput = (props) => <div>
<C {...props} />
<span>{props.errors.join(', ')}</span>
</div>
}
export default FormInputHOC(TextInput)
2) 包装器
const FormInput = (props) => <div>
{props.children}
<span>{props.errors.join(', ')}</span>
</div>
const TextInput = (props) => <FormInput errors={props.errors}>
<input type="text" {...props} />
</FormInput>
在你的情况下,没有真正的区别,但是当你想对组件状态进行操作时,HOC 允许你编写可以在 this.state
上工作的函数。此状态将是 HOC 包装的组件之一。
示例:
使用 HOC,您可以编写一个 componentWillReceiveProps()
函数,每当组件接收到 props 时,该函数将在组件状态上添加或删除一些数据。您可以在多个组件上使用此 HOC。