reactjs - 如何将动态创建的选项标记为选项列表中使用的选项
问题描述
我想从列表中动态呈现选择中的选项。如果选项已使用,我想将其标记为isUsed: true
. 我的意思是改变状态<Wrapper />
this.state = {
options: {
One: {value: "one", isUsed: false},
Two: {value: "two", isUsed: false},
Three: {value: "three", isUsed: false}
}
什么是最好的方法?
我正在尝试使用componentDidMount()
using标记它markUsed()
(出于测试目的,有静态键"One"),但是如何获得当前已安装的选项,以标记动态键this.state
?我试过console.log(this)
in componentDidMount()
,但它似乎不包含当前安装的选项值。
import React from 'react';
import ReactDOM from 'react-dom';
class Input extends React.Component {
componentDidMount = () => {
console.log(this);
this.props.markUsed();
}
render() {
let options = Object.keys(this.props.list).map((item,i) => {
if (!this.props.list[item].isUsed) {
return(
<option key={i} value={this.props.list[item].value}>{item}</option>
)
}
});
return (
<div>
<select>
{options}
</select>
<input type="text" />
</div>
)
}
}
class Wrapper extends React.Component {
constructor(props) {
super(props);
this.markUsed = this.markUsed.bind(this);
this.state = {
options: {
One: {value: "one", isUsed: false},
Two: {value: "two", isUsed: false},
Three: {value: "three", isUsed: false}
},
inputs: []
}
}
markUsed = () => {
this.setState(prevState =>({
options: {
...prevState.options,
One: {
...prevState.options.One,
isUsed: true
}
}
}));
}
addInput = (e) => {
this.setState((prevState) => ({
inputs: [...prevState.inputs, {option: "", value: ""}],
}));
}
render() {
return(
<div>
{
this.state.inputs.map((val, idx) => {
return (
<div key={idx}>
<Input list={this.state.options} markUsed={this.markUsed} />
</div>
)
})
}
<button type="button" onClick={this.addInput}>add</button>
</div>
)
}
}
ReactDOM.render(<Wrapper />, document.getElementById('root'));
解决方案
这是一个通用解决方案,您可以在其中传递target
要标记的 a:
markUsed = target => {
const [key, keyValue] = Object.entries(this.state.options).find(
([, keyValue]) => keyValue.value === target
);
keyValue.isUsed = true;
this.setState(prevState => ({
...prevState,
options: { ...prevState.options, [key]: keyValue }
}));
};
因此,您需要传递一个目标值,如,one
等。two
three
class Input extends React.Component {
state = {
...
};
render() {
const { markUsed } = this.props;
const options = Object.keys(this.props.list).map((item, i) => {
if (!this.props.list[item].isUsed) {
if (this.props.list[item].value === this.state.currValue) {
markUsed(this.state.currValue);
}
return ...
}
});
return (
<>
<select
value={this.state.value}
onChange={e => {
e.persist();
const currValue = e.target.value;
markUsed(currValue);
this.setState({ currValue });
}}
>
...
</>
);
}
}
推荐阅读
- python - 在 pythonanywhere.com 中使用 python3.8 和 django3.1 手动 webapp
- r - 当变量是R中的时间序列时修改x轴参数
- flutter - Flutter:当文本表单字段获得或失去焦点时如何显示或隐藏标签/文本小部件?
- javascript - 无限循环的问题
- c# - 用于安装驱动程序的 C# WinForms 或 WPF 应用程序复选框列表
- curl - 如何使用 curl 获取有关操作系统和 Web 服务器的信息
- postgresql - 所有者和用户的 Postgres 关系
- php - 防止网站被视为 IP
- c# - 如何控制 Lerp 速度?
- r - 使用ggplot多线和中心对齐x轴标签