reactjs - 如何在reactjs中更新地图功能中的状态
问题描述
我有 4 个按钮,每个按钮都有名称 id 和选定的布尔标志。
我想要实现的是,单击按钮时,应该更改该特定按钮的布尔按钮标志。为此,我需要在地图函数中为该特定按钮 ID 设置状态。
我的问题是我无法在地图功能中为那个特定的点击按钮设置状态,它的 btnSelected 应该改变
我的目标是创建一个多选取消选择按钮。它为用户提供了一种兴趣选择,并在此基础上反映了 UI 以及我的数组。这是我的代码。
感谢期待。
import React, { Component } from "react";
import { Redirect } from "react-router-dom";
export default class Test extends Component {
constructor(props, context) {
super(props, context);
this.handleChange = this.handleChange.bind(this);
this.state = {
value: "",
numbers: [1, 2, 3, 4, 5],
posts: [
{
id: 1,
topic: "Animal",
btnSelected: false
},
{
id: 2,
topic: "Food",
btnSelected: false
},
{
id: 3,
topic: "Planet",
btnSelected: false
},
{ id: 4, topic: "Nature", btnSelected: false }
],
allInterest: []
};
}
handleChange(e) {
//console.log(e.target.value);
const name = e.target.name;
const value = e.target.value;
this.setState({ [name]: value });
}
getInterest(id) {
this.state.posts.map(post => {
if (id === post.id) {
//How to setState of post only btnSelected should change
}
});
console.log(this.state.allInterest);
if (this.state.allInterest.length > 0) {
console.log("Yes we exits");
} else {
console.log(id);
this.setState(
{
allInterest: this.state.allInterest.concat(id)
},
function() {
console.log(this.state);
}
);
}
}
render() {
return (
<div>
{this.state.posts.map((posts, index) => (
<li
key={"tab" + index}
class="btn btn-default"
onClick={() => this.getInterest(posts.id)}
>
{posts.topic}
<Glyphicon
glyph={posts.btnSelected === true ? "ok-sign" : "remove-circle"}
/>
</li>
))}
</div>
);
}
}
解决方案
以下是你如何做这样的事情:
class App extends Component {
state = {
posts: [{
name: 'cat',
selected: false,
}, {
name: 'dog',
selected: false
}]
}
handleClick = (e) => {
const { posts } = this.state;
const { id } = e.target;
posts[id].selected = !this.state.posts[id].selected
this.setState({ posts })
}
render() {
return (
<div>
<form>
{this.state.posts.map((p, i) => {
return (
<div>
<label>{p.name}</label>
<input type="radio" id={i} key={i} checked={p.selected} onClick={this.handleClick} />
</div>
)
})}
</form>
</div>
);
}
}
render(<App />, document.getElementById('root'));
这里的工作示例。
推荐阅读
- javascript - Base64 PDF 数据 IE 和 Edge 不显示
- python - ValueError:无法为具有形状“(?,784)”的张量“Placeholder:0”提供形状(1,10712)的值
- npm - npm install global vs local 安装不同的东西
- ios - Swift 执行顺序 ViewController UIKit
- javascript - 从 ReactJs 中的变量生成选择选项条目
- javascript - 如何修复加载本地 JSON 提取的错误?
- twitter-bootstrap - 如何将 bootstrap css 和 js 与我的 liferay 7.2 主题集成?
- javascript - 反应:setState() 钩子,未设置初始颜色
- r - 将多行的json文件转换为R数据框
- python - Python Tkitner 删除菜单栏下的小间距