如何在 React 中将动态值从父级传递给子级?

How to pass a dynamic value from parent to child in React?

所以我的 App.js 文件如下所示:

import React from "react";
import { useState } from "react";
import './App.css';
import Header from "./components/pages/Header";
import NAV from "./NAV";
import Trees from "./components/tree";


function App() {
 
    
      const [inputField , setInputField] = useState({
        first_name: 'Phyag_NZFS3770'
    })
   
    const inputsHandler = (e) =>{
        setInputField( {[e.target.name]: e.target.value} )
    }

    const submitButton = () =>{
        alert(inputField.first_name)
        

    }
  


return(
<div className="App">
      <NAV genomename={inputField.first_name}/> //this can't be done as the prop value is undefined
      <Header title="EumicrobeDB"/>
      <h3 style={{ textAlign:"left" }}> Organism List </h3>  
        <div> <Trees /> </div>
          <div>
            <input 
            type="text" 
            name="first_name" 
            onChange={inputsHandler} 
            placeholder="enter the organism id" 
            value={inputField.first_name}/>
            <button onClick={submitButton}>Submit Now</button> 
        </div>
    </div>
    )

    
  } 
export default App;

任何人都可以修改代码以将{inputField.first_name}作为道具值传递给我的名为NAV的函数吗?我处于绝对固定状态..我是一名刚接触 React 的生物学家;谁必须在截止日期前完成

这是将数据作为 props.

从父组件传递到子组件的方法

例子

import React from "react";
import { useState } from "react";

const Header = ({ title }) => {
  return <React.Fragment>Hello, {title}</React.Fragment>;
};

function App() {
  const [inputField, setInputField] = useState({
    first_name: "Phyag_NZFS3770"
  });

  const inputsHandler = (e) => {
    console.log([e.target.name] , e.target.value);
    setInputField({ [e.target.name]: e.target.value });
  };

  const submitButton = () => {
    alert(inputField.first_name);
  };

  return (
    <div className="App">
      <Header title={inputField.first_name} />
      <h3 style={{ textAlign: "left" }}> Organism List </h3>
      <div>
        <input
          type="text"
          name="first_name"
          onChange={inputsHandler}
          placeholder="enter the organism id"
          value={inputField.first_name}
        />
        <button onClick={submitButton}>Submit Now</button>
      </div>
    </div>
  );
}
export default App;

您在此组件中的代码按原样看起来不错。确保您访问的是 props.genomename 而不是 NAV 组件中的 props.first_name

如果您打算添加更多输入字段,我还建议您更改 inputHandler 函数以与之前的状态合并,而不是完全替换它:

const inputsHandler = (e) => {
    setInputField({ ...inputField, [e.target.name]: e.target.value })
}