在React JS中从子组件传值给父组件。

huangapple go评论54阅读模式
英文:

Passing value from child component to parent component in React JS

问题

我只是开始使用React,并尝试创建“待办事项列表”,现在我需要将子功能组件中的输入值传递给父功能组件,但不知道如何做。

我需要从“Form”组件传递“value”到“App”组件,以将新值添加到值数组中,但组件位于不同的文件中。

父组件代码:

const App = () => {
  const [items, setItems] = React.useState([
    'First To Do',
    'Second To Do',
    'Third To Do',
  ]);

  return (
    <div className='app'>
      <Form />
      <ToDoList items={items} />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

子组件代码:

const Form = () => {
  const [value, setValue] = React.useState('');

  function handleValueChange(e) {
    setValue(e.target.value);
  }

  function handleSubmit(e) {
    e.preventDefault();
    console.log(value);
    alert('New To Do was added.');
    setValue('');
  }

  return (
    <div className={classes.addingForm}>
      <form onSubmit={handleSubmit}>
        <input className={classes.myInput} type='text' value={value} onChange={handleValueChange}/>
        <input className={classes.mySubmit} type='submit' value='Submit' />
      </form>
    </div>
  )
};

export default Form;

希望这对你有所帮助!

英文:

I'm only starting to work with React and now trying to create "To Do List", now I need to pass value from input in child functional component to parent functional component, but don't know how to do that.

I need to pass 'value' from 'Form' component to 'App' component to add new value to values array, but components are in different files.

Parent component code:

const App = () =&gt; {

  const [items, setItems] = React.useState([
  &#39;First To Do&#39;,
  &#39;Second To Do&#39;,
  &#39;Third To Do&#39;,
  ]);  

  return (

   &lt;div className=&#39;app&#39;&gt;
    &lt;Form /&gt;
    &lt;ToDoList items={items} /&gt;
   &lt;/div&gt;

  );

}

const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));

root.render(
 &lt;React.StrictMode&gt;
   &lt;App /&gt;
 &lt;/React.StrictMode&gt;
);

Child component code:

const Form = () =&gt; {
  const [value, setValue] = React.useState(&#39;&#39;);

  function handleValueChange(e) {
    setValue(e.target.value);
  }

  function handleSubmit(e) {
    e.preventDefault();
    console.log(value);
    alert(&#39;New To Do was added.&#39;);
    setValue(&#39;&#39;);
  }


  return (
    &lt;div className={classes.addingForm}&gt;
        &lt;form onSubmit={handleSubmit}&gt;
            &lt;input className={classes.myInput} type=&#39;text&#39; value={value} onChange={handleValueChange}/&gt;
            &lt;input className={classes.mySubmit} type=&#39;submit&#39; value=&#39;Submit&#39; /&gt;
        &lt;/form&gt;
    &lt;/div&gt;
  )

};

export default Form;

答案1

得分: 1

在 App 组件中定义了 value 和 setValue,并将其作为 props 传递给 Form 组件。

// App.js

const App = () => {
    const [items, setItems] = React.useState([
        "First To Do",
        "Second To Do",
        "Third To Do",
    ]);
    const [value, setValue] = React.useState("");

    useEffect(() => {
        // 如果表单提交,您可以在此处记录新值
        console.log(value);
    }, [value]);

    return (
        <div className="app">
            <Form setValue={setValue} />
            <ToDoList items={items} />
        </div>
    );
};

// 子组件代码:

const Form = ({ setValue }) => {
    function handleValueChange(e) {
        setValue(e.target.value);
    }

    function handleSubmit(e) {
        e.preventDefault();
        console.log(value);
        alert("New To Do was added.");
        setValue("");
    }

    return (
        <div className={classes.addingForm}>
            <form onSubmit={handleSubmit}>
                <input
                    className={classes.myInput}
                    type="text"
                    value={value}
                    onChange={handleValueChange}
                />
                <input
                    className={classes.mySubmit}
                    type="submit"
                    value="Submit"
                />
            </form>
        </div>
    );
};

export default Form;
英文:

Define value and setValue in the App component and pass it as props to Form component

// App.js

const App = () =&gt; {
    const [items, setItems] = React.useState([
        &quot;First To Do&quot;,
        &quot;Second To Do&quot;,
        &quot;Third To Do&quot;,
    ]);
    const [value, setValue] = React.useState(&quot;&quot;);

    useEffect(() =&gt; {
        // you can log the new value here if the form is submitted
        console.log(value);
    }, [value]);

    return (
        &lt;div className=&quot;app&quot;&gt;
            &lt;Form setValue={setValue} /&gt;
            &lt;ToDoList items={items} /&gt;
        &lt;/div&gt;
    );
};

// Child component code:

const Form = ({ setValue }) =&gt; {
    function handleValueChange(e) {
        setValue(e.target.value);
    }

    function handleSubmit(e) {
        e.preventDefault();
        console.log(value);
        alert(&quot;New To Do was added.&quot;);
        setValue(&quot;&quot;);
    }

    return (
        &lt;div className={classes.addingForm}&gt;
            &lt;form onSubmit={handleSubmit}&gt;
                &lt;input
                    className={classes.myInput}
                    type=&quot;text&quot;
                    value={value}
                    onChange={handleValueChange}
                /&gt;
                &lt;input
                    className={classes.mySubmit}
                    type=&quot;submit&quot;
                    value=&quot;Submit&quot;
                /&gt;
            &lt;/form&gt;
        &lt;/div&gt;
    );
};

export default Form;

huangapple
  • 本文由 发表于 2023年1月8日 23:14:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定