【发布时间】:2019-07-27 12:15:34
【问题描述】:
我有一个名为 InputWithButton 的自定义组件,如下所示:
const InputWithButton = ({ type = "text", id, label, isOptional, name, placeholder = "", value = "", showPasswordReset, error, isDisabled, buttonLabel, handleChange, handleBlur, handleClick }) => (
<StyledInput>
{label && <label htmlFor="id">{label}{isOptional && <span className="optional">optioneel</span>}</label>}
<div>
<input className={error ? 'error' : ''} type={type} id={id} name={name} value={value} placeholder={placeholder} disabled={isDisabled} onChange={handleChange} onBlur={handleBlur} autoComplete="off" autoCorrect="off" />
<Button type="button" label={buttonLabel} isDisabled={isDisabled} handleClick={() => handleClick(value)} />
</div>
{error && <Error>{Parser(error)}</Error>}
</StyledInput>
);
export default InputWithButton;
Button 是另一个组件,如下所示:
const Button = ({ type = "button", label, isLoading, isDisabled, style, handleClick }) => (
<StyledButton type={type} disabled={isDisabled} style={style} onClick={handleClick}>{label}</StyledButton>
);
export default Button;
我在这样的父组件中使用 InputWithButton 组件:
render() {
const { name } = this.state;
return (
<React.Fragment>
<InputWithButton label="Name" name="Name" buttonLabel="Search" value={name} handleChange={this.handleChange} handleClick={this.searchForName} />
</React.Fragment>
);
}
如果点击按钮,则调用searchForName函数:
searchForName = value => {
console.log(value); //Input field value
}
这是可行的,但我想向它添加另一个参数,但这次是来自父组件的参数
// handleClick={() => this.searchForName('person')}
<InputWithButton label="Name" name="Name" buttonLabel="Search" value={name} handleChange={this.handleChange} handleClick={() => this.searchForName('person')} />
searchForName 中的输出现在是“人”而不是值。
我想我可以用以下代码解决这个问题:
searchForName = type => value => {
console.log(type); //Should be person
console.log(value); //Should be the value of the input field
}
但是这种方法不再执行该功能。
我该如何解决这个问题?
编辑:Codepen
【问题讨论】:
-
this.searchForName('person')} 只是调用带有 'person' 参数的函数 searchForName - 该函数只是将这个参数记录下来。您期望的价值是多少?
-
@DaleKing 我期待我从父组件传递的值是“人”,而我在
InputWithButton中传递的值是“输入值”字段. -
啊,我明白你的意思了。你能抛出一个包含相关部分的代码沙箱吗?
-
@DaleKing 我添加了一个 Codepen 链接。 codepen.io/anon/pen/YgpOGE
标签: javascript reactjs ecmascript-6 arrow-functions