javascript - React - 如何从父组件中的函数制作组件?
问题描述
React 新手 - 我有一个组件 AddForm,如下所示:
class AddForm extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
};
}
handleInput = event => {
this.setState({ name: event.target.value });
};
logValue = () => {
console.log(this.state.name)
return <Display text={this.state.name} />
};
render() {
return (
<div>
<input onChange={this.handleInput}
placeholder="Type Here" type="text" />
<button onClick={this.logValue}
type="submit">Submit</button>
</div>
)
}
}
当用户单击“提交”按钮时,我希望它显示表单中的内容。我将值存储在 this.state.name 中的表单中,用于在表单内显示文本的组件如下所示:
class Display extends React.Component {
render() {
return (
<h1>{this.props.text}</h1>
)
}
}
我知道我的 state.name 可以访问表单,因为我 console.logged 它。我只想知道为什么我在 AddForm 组件的 logValue 函数中的 return 语句没有创建一个新组件 Display,我怎样才能让它工作?
解决方案
单击按钮应该会导致状态更改,然后 render 方法会使用该状态更改来返回 Display 组件 - 类似于:
logValue = () => {
this.setState({ showingName: !this.state.showingName });
}
render() {
return (
<div>
{
this.state.showingName ? <Display text={this.state.name} /> : null
}
<input onChange={this.handleInput}
placeholder="Type Here" type="text" />
<button onClick={this.logValue}
type="submit">Submit</button>
</div>
)
}
推荐阅读
- r - R Studio 折叠不保存
- python - m4 皮质处理速度与桌面处理器的粗略估计
- putty - MSP430,无法使用 UART no Output with Putty
- elasticsearch - CQRS 为什么不只为读写提供弹性搜索?
- matrix - 如何在区域的扩展区域内找到一个点?
- php - 无法将 MySQL 连接到 XAMPP
- laravel - Laravel Echo 存在通道与 vue 路由器无法正常工作
- javascript - `message` 字段值未在 NodeJS 中的 `CustomError` 类中设置,通过函数构造函数进行经典继承
- mysql - 在 MySQL 中创建关系
- sql - 计算每个月的成本 SQL