[英]How to add context to recompose's withHandlers()?
recompose
has this function called withHandlers
that lets you define an event handler while keeping your component pure. recompose
具有一个称为withHandlers
函数,该函数可让您定义事件处理程序,同时保持组件的纯净。
eg if you had something like this inside you render()
method: 例如,如果在您的
render()
方法内部有这样的内容:
<TextInput value={value} onChange={ev => this.handleChange(ev.target.value)} />
it wouldn't be pure because every time your component renders, it'd by passing a different onChange
function to your TextInput
component. 这不是纯粹的,因为每次渲染组件时,都是通过将不同的
onChange
函数传递给TextInput
组件来实现的。
This is great, but how can this be extended to support arrays of inputs? 很好,但是如何扩展它以支持输入数组? Or otherwise provide auxiliary data?
还是提供辅助数据?
eg taking their example and extending it a bit: 例如以他们的例子并扩展一下:
const enhance = compose(
withState('values', 'updateValue', ''),
withHandlers({
onChange: props => inputName => event => {
props.updateValue(inputName, event.target.value)
},
onSubmit: props => event => {
event.preventDefault();
submitForm(props.value)
}
})
)
const Form = enhance(({ value, onChange, onSubmit, inputs }) =>
<form onSubmit={onSubmit}>
<label>Value
{inputs.map(input => (
<TextInput value={value} onChange={onChange(input)} />
))}
</label>
</form>
)
I've fudged the details a bit, but pretend inputs
comes in as an array of input names. 我已经对细节进行了一些改动,但是假装
inputs
作为输入名称的数组出现。 eg ["firstName","lastName"]
would render two textboxes, one for each. 例如
["firstName","lastName"]
将呈现两个文本框,每个文本框一个。
I want to store the values for each of these in my state, but I don't want to define separate updater functions for each. 我想在我的状态下存储每个值,但是我不想为每个值定义单独的更新程序功能。 Thus I need to attach some metadata to the
onChange={...}
prop so that I know which field I'm updating in my state. 因此,我需要将一些元数据附加到
onChange={...}
道具上,以便我知道我正在更新哪个字段。
How can I do that? 我怎样才能做到这一点?
In my example I wrote onChange(input)
and added an extra 'level' to the withHandlers.onChange
function to accept the extra argument, but withHandlers
doesn't actually work that way. 在我的示例中,我编写了
onChange(input)
并在withHandlers.onChange
函数中添加了一个额外的“级别”来接受额外的参数,但是withHandlers
实际上并不能以这种方式工作。 Is there some way to do this -- ie, ensure that each TextInput
receives the same function instance every time <Form>
is rendered? 有什么方法可以做到这一点-即确保每次呈现
<Form>
时,每个TextInput
接收相同的函数实例?
That's a typical case where you need to define the change handle directly inside your TextInput component. 这是典型的情况,您需要直接在TextInput组件内部定义更改句柄。 You'd need to pass updateValue function as a prop to TextInput components.
您需要将updateValue函数作为对TextInput组件的支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.