首页 > 解决方案 > 我无法在 React 中将道具从父母传递给孩子

问题描述

从 react 开始,我在父组件中创建了一个输入字段,当用户提交文本时,我将文本传递给子组件并在父组件下打印文本。

父组件代码

import React, { useState } from "react";
import Validate from "./Validate";

function CommandEntry() {
  const [value, setValue] = useState("");
  const handleSubmit = e => {
    e.preventDefault();
    // console.log(value);
    return <Validate value={value} />;
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        enter text:~
        <input
          type="text"
          autoFocus
          required
          onChange={e => setValue(e.target.value)}
        />
      </form>
    </div>
  );
}

export default CommandEntry;

子组件代码

import React from "react";

export default function Validate(props) {
  console.log("I am in child");
  return (
    <div>
      <h1>{props.value}</h1>
    </div>
  );
}

标签: javascriptreactjs

解决方案


您将需要render里面的孩子return并在处理程序中设置值。

像这样:

function CommandEntry() {
  const [value, setValue] = useState("");
  const [submit, setSubmitValue] = useState(false);
  const handleChange = e => {
    e.preventDefault();
    setValue(e.target.value); //setting the value on change

  };
  const handleSubmit = e => {
    e.preventDefault();
    setSubmitValue(true); //setting the submit flag to true.
  };
  return (
    <div>
      value &&
      <form onSubmit={handleSubmit}> // submit handler
        enter text:~
        <input
          type="text"
          autoFocus
          required
          onChange={handleChange} // change handler
        />
       {submit && 
        <Validate value={value} /> // rendering the child component 
       }
      </form>
    </div>
  );
}

推荐阅读