【问题标题】:How can I send the data to the parent component by click on the button in React?如何通过单击 React 中的按钮将数据发送到父组件?
【发布时间】:2022-11-04 02:06:49
【问题描述】:

我的问题是如何通过单击按钮将输入值发送到父组件?因为现在如果我在输入中输入一些东西,它会立即改变值,我希望它在我单击按钮后执行。

目前我正在使用该方法:

const FormInput = ({setIpAddress}) => {     
    return (
        <div className="formInput">
            <form className="form_container" onSubmit={e => {e.preventDefault();}}>
                <input type="text" id="input" onChange={(e) => setIpAddress(e.target.value)} required={true} placeholder="Search for any IP address or domain"/>
                <button type="submit" className="input_btn">
                    <img src={arrow} alt="arrow"/>
                </button>
            </form>
        </div>
    );
};

export default FormInput

【问题讨论】:

    标签: reactjs input react-props


    【解决方案1】:

    您可以将onClick 回调函数传递给子组件。调用此函数时,它将触发子项中的重新渲染。

    例子:

    家长:

    const handleClick = (value) => {
      //set the state here
    }
    
    <ChildComponent onClick={handleClick} />
    

    孩子:

     <button type="submit" className="input_btn" onClick={(value) => props.onClick?.(value)}>
    

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      相关资源
      最近更新 更多