javascript - 如何在点击反应时显示数据
问题描述
实现了将数据从表单写入数组。一切正常。但是现在我想实现当我点击“SEND ARR”时的数据输出当我分别点击一个按钮时,数据不显示,因为在我们访问的函数中 event.target.value
请告诉我如何重写该行以便单击按钮时可以显示数据?谢谢
主页.js
import React from "react";
import "./../App.css"
export default class Home extends React.Component {
constructor() {
super()
this.state = {
count: 1,
objexm: '',
inputValue: '',
arr: []
}
this.handleClick = this.handleClick.bind(this);
this.updateInputValue = this.updateInputValue.bind(this);
}
handleClick() {
this.setState({
count: this.state.count + 1
});
};
createMarkup() {
return {
__html: this.state.inputValue
};
};
updateInputValue(event) {
let newArr = this.state.arr;
let newlist = event.target.value;
if (event.target.value) {
newArr.push(newlist)
}
this.setState({
inputValue: newArr
});
event.target.value = '';
};
render() {
return (
<div className="home-header">
<h2>{this.state.count}</h2>
<button onClick={this.handleClick}>Add</button>
<input type='text' name="names" onClick={this.updateInputValue} />
{this.state.arr.map((arrs, index) => {
return (
<li
key={index}
>{arrs}</li>
)
})}
<button>SEND ARR</button>
<ul className="qwe">
<li dangerouslySetInnerHTML={this.createMarkup()}></li>
</ul>
</div>
);
}
}
解决方案
不是onClick
在输入上使用,而是onChange
在状态中使用和更新值,即使输入成为受控组件。发布按钮的 onClick 从状态中获取值并推送到数组并清除输入值
export default class Home extends React.Component {
constructor() {
super()
this.state = {
count: 1,
objexm: '',
inputValue: '',
arr: []
}
this.handleClick = this.handleClick.bind(this);
this.updateInputValue = this.updateInputValue.bind(this);
}
handleClick() {
this.setState(prevState => ({
count: prevState.count + 1,
inputValue: [...prevState.inputValue, prevState.name],
name: ""
}));
};
createMarkup() {
return {
__html: this.state.inputValue
};
};
updateInputValue(event) {
let newVal = event.target.value;
this.setState({
name: newVal
});
};
render() {
return (
<div className="home-header">
<h2>{this.state.count}</h2>
<button onClick={this.handleClick}>Add</button>
<input type='text' name="names" value={this.state.name} onChange={this.updateInputValue} />
{this.state.arr.map((arrs, index) => {
return (
<li
key={index}
>{arrs}</li>
)
})}
<button>SEND ARR</button>
<ul className="qwe">
<li dangerouslySetInnerHTML={this.createMarkup()}></li>
</ul>
</div>
);
}
}
推荐阅读
- docker - 使用 Dockerfile 在 700 (drwx------) 目录下创建文件
- javascript - 在javascript中从json读取数据并过滤数据
- linear-algebra - 基本计算问题:指数表达式
- ios - 在 Swift 中转换视频文件时如何设置最小输出大小?
- python-3.x - AWS Lambda 未在 Python 3.8 中显示原因异常堆栈跟踪
- javascript - 从服务器端获取信息到我的前端
- firebase - TypeError:未定义不是对象(评估事件[0].name)
- haskell - Haskell 高阶函数和关联性
- reactjs - 将附加参数传递给 GET_ONE
- php - 如何使用 PHP 从一对多 sql 关系中检索数据