javascript - 我无法在 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>
);
}
解决方案
您将需要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>
);
}
推荐阅读
- python - 如何在 Django 中以单一形式上传多个文件?
- javascript - 关于Axios的使用
- amazon-web-services - 在 puresec 的函数屏蔽上检测到空的 aws lambda 子进程执行
- wcf - 收到错误“合同不匹配 - 发送方和接收方之间的操作不匹配”
- c++ - 非类型模板参数:从 bool 到 int 的隐式转换有效,但从 double 到 int 无效。这是为什么?
- nativescript - 如何:使用 Webpack 自定义 CSS 文件?(本机脚本)
- php - Laravel:OVH 托管 SQLSTATE [HY000] [2002] 连接超时
- c++ - 调用哪个字符串构造函数?
- reactjs - 是否可以使用 redux-form、connect 和 withRouter?
- javascript - 未处理的拒绝(SyntaxError):意外的令牌 < 在 JSON 中的位置 0 React