将带有函数的参数发送到子组件并返回到父组件

时间:2019-03-05 22:46:06

标签: javascript reactjs ecmascript-6 arrow-functions

我有一个名为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中的输出现在是'person'而不是值。

我以为可以用以下代码解决此问题:

searchForName = type => value => {
    console.log(type); //Should be person
    console.log(value); //Should be the value of the input field
}

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

我该如何解决?

编辑:Codepen

2 个答案:

答案 0 :(得分:0)

我会尝试handleClick={this.searchForName.bind(this, 'person')},请告诉我它是否适合您。

编辑: 我从您的Codepen中更改了片段,它可以正常工作:

searchName(key, value) {
    console.log(key);
    console.log(value);
  }

  render() {
    const { name } = this.state;

    return (
      <InputWithButton name="name" value={name} buttonLabel="Search" handleChange={this.handleChange} handleClick={this.searchName.bind(this, 'person')} />
    )
  }

答案 1 :(得分:0)

正如我所怀疑的,只需向其传递一个对象,并确保您接受handleClick函数中的参数

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

或更冗长-没有语法糖

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

那么您就可以用value.person

完整的codepen here

希望这会有所帮助