首页 > 解决方案 > 将带有函数的参数发送给子组件并返回给父组件

问题描述

我有一个名为的自定义组件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
}

但是,这种方法不再执行该功能。

我怎样才能解决这个问题?

编辑:代码笔

标签: javascriptreactjsecmascript-6arrow-functions

解决方案


正如我所怀疑的那样,只需将它传递给一个对象并确保您接受了 handleClick 函数中的参数

handleClick={value => this.searchName({value, person: 'person'})}

或更冗长 - 没有语法糖

handleClick={value => this.searchName({value: value, person: 'person'})}

然后你可以用 value.person 来解决它

完整的codepen在这里

希望这可以帮助


推荐阅读