所以我的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;
这个组件中的代码看起来很好。确保在NAV组件中访问props.genomename
而不是props.first_name
。
如果您打算添加更多的输入字段,我还建议您更改inputHandler函数以与之前的状态合并,而不是完全替换它:
const inputsHandler = (e) => {
setInputField({ ...inputField, [e.target.name]: e.target.value })
}