javascript - 将带有函数的参数发送给子组件并返回给父组件
问题描述
我有一个名为的自定义组件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
}
但是,这种方法不再执行该功能。
我怎样才能解决这个问题?
编辑:代码笔
解决方案
正如我所怀疑的那样,只需将它传递给一个对象并确保您接受了 handleClick 函数中的参数
handleClick={value => this.searchName({value, person: 'person'})}
或更冗长 - 没有语法糖
handleClick={value => this.searchName({value: value, person: 'person'})}
然后你可以用 value.person 来解决它
希望这可以帮助
推荐阅读
- sql-server - 与单个主键有多个关系的表
- java - OpenAPI Generator:为下载二进制文件生成正确的方法配置文件
- arrays - 将在excel中返回长数字的vba数组转换为字符串,即数组(67、1)
- audio - MPEG 音频恒定比特率转换
- jquery - 如何在请求 httpget 时显示加载文本?
- heroku - 预期的不可空类型字符串!在 value.workspaceSlug 处不为空
- python - 如何获取控制台中显示的文本
- asp.net - 如何正确地将脚本添加到 ASP.NET Core 局部视图?
- c# - 如何在我的 azure Web 应用程序机器人上解决 401?
- apache - Rewriterule 从 url 中删除 index.php for codeigniter 导致重定向过多