我有反应状态。提交表单后,我想将输入值发送到其他组件,然后显示给浏览器。我成功提交了表单,但是当我将porps发送到其他组件时。它什么也没显示。
这是我的英雄组成部分
import React from "react";
import "./App.css";
import Show from "./Show";
function App() {
const [state, setState] = React.useState({
input: " ",
text: " "
});
const changeHandler = e => {
setState({ ...state, [e.target.id]: e.target.value });
};
const handleSubmit = e => {
e.preventDefault();
console.log(state);
return <Show show={state} />; //this is the component where I am sending props
};
return (
<React.Fragment>
<div className="row">
<form className="col s12" onSubmit={handleSubmit}>
<div className="row">
<div className="input-field col s3">
<input
id="input"
type="text"
data-length="4"
onChange={changeHandler}
/>
<label htmlFor="input_text">Input text</label>
</div>
</div>
<div className="row">
<div className="input-field col s8">
<textarea
id="text"
className="materialize-textarea"
data-length="120"
onChange={changeHandler}
></textarea>
<label htmlFor="textarea2">Right your text</label>
</div>
</div>
<button
className="btn waves-effect blue lighten-1"
type="submit"
name="action"
>
Submit
</button>
</form>
<Show /> //After submit the form I want to show to the browser
</div>
</React.Fragment>
);
}
export default App;
这是我的子组件。
import React from "react";
export default function Show({ show }) {
return (
<div>
{show ? (
<ul>
<li>{show.input}</li>
<li>{show.text}</li>
</ul>
) : null}
</div>
);
}
ps:忽略此消息。要上传此帖子,我需要这样做。写更多😀。
调用方法错误
handleSubmit
是事件活动调用。它不是组件handleSubmit
组件内部返回不正确的那个因此,父片段内Show
组件的传递状态值更好)>
const handleSubmit = e => {
e.preventDefault();
console.log(state);
};
return (
<React.Fragment>
<div className="row">
<form className="col s12" onSubmit={handleSubmit}>
<div className="row">
<div className="input-field col s3">
<input
id="input"
type="text"
data-length="4"
onChange={changeHandler}
/>
<label htmlFor="input_text">Input text</label>
</div>
</div>
<div className="row">
<div className="input-field col s8">
<textarea
id="text"
className="materialize-textarea"
data-length="120"
onChange={changeHandler}
></textarea>
<label htmlFor="textarea2">Right your text</label>
</div>
</div>
<button
className="btn waves-effect blue lighten-1"
type="submit"
name="action"
>
Submit
</button>
</form>
<Show show={state} /> //pass state directly
</div>
</React.Fragment>
);