reactjs - 从输入组件中获取值并在 React 中的另一个组件中使用它
问题描述
我是 React 的新手,并且有这个简单的代码示例,我只需要从输入中获取值并将值显示回来。
class App extends React.Component {
constructor(props){
super(props);
this.state = { word : ""};
this.onClick = this.onClick.bind(this);
}
onClick(e){
this.setState({word : /* how to obtain input value?? */});
}
render() {
return (
<>
<form>
<input type="text"/>
<button onClick={this.onClick}>Say it!</button>
</form>
<div>
{this.state.word}
</div>
</>
);
}
}
我知道反应希望我使用组件状态作为将信息从父组件传播到其子组件的一种方式。我不知道我应该如何获得一个孩子的状态以用于另一个孩子。
我相信这应该以简单的方式做出反应,因为使用纯 DOM 或 JQuery 的等效方式也非常简单(一两行代码)。
解决方案
您可以使用createRef
import React, { createRef } from "react";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { word: "" };
this.onClick = this.onClick.bind(this);
}
textInput = createRef();
onClick(e) {
this.setState({ word: this.textInput.current.value });
}
render() {
return (
<div className="App">
<form>
<input ref={this.textInput} type="text" />
<button onClick={this.onClick} type="button">
Say it!
</button>
</form>
<div>{this.state.word}</div>
</div>
);
}
}
export default App;
在这里检查CodeSandBox
推荐阅读
- php - 根据表单数据和传递的值执行插入的函数
- python - Scrapy+Tkinter -> exe cx freeze(编译成exe后scrapy函数不起作用)
- angular - Angular 6. 如何在创建的 CustomControl 中给定 Validator 状态这个控件?
- sql - 红移计数(DISTINCT())。计算每个 ID 的唯一日期
- ruby-on-rails - 为什么不能在辅助函数中使用 form_tag 和 form_for [Rails]
- spring - Spring Batch Late Binding Within SQL Using Java Config
- java - 进行二分查找时如何设置中间元素?
- mysql - 如何找到用户点击的第二家不同的酒店
- sql - oracle sql行数减去运行量
- c# - ASP.NET C# 中的 Outlook