javascript - 反应从输入字段填充下拉列表
问题描述
我有一个简单的 React 应用程序,它允许您在单击按钮时创建多个“故事”组件。每个“故事”都有两个组件 - 一个输入字段(用于编辑故事标题)和一个下拉列表(显示所有其他故事标题)。
我试图让故事下拉列表填充所有故事标题(目前它们被硬编码到一个名为storyOptions的状态数组中)。
最终的想法是 - 用户创建新故事 > 用户更新故事标题 > 用户从下拉列表中选择要链接到的另一个故事(下拉列表显示所有其他故事的标题)。
我当前的代码如下...
class App extends Component {
constructor(props) {
super(props);
this.storyList = [];
this.state = {storys: this.storyList};
}
addNewStory(e) {
this.storyList.push({
id: this.storyList.length,
title:"Type your story title here",
});
this.setState({storys: this.storyList});
}
render() {
return (
<div>
<button className="square" onClick={() => this.addNewStory()}>
"Add new story"
</button>
<div>
{this.state.storys.map(c => <StoryComponent key={c.id} title={c.title} />)}
</div>
</div>
);
}
}
export default class StoryComponent extends Component {
constructor(props) {
super(props);
this.state = {
defaultStoryOption: 0,
title: this.props.title
};
this.storyOptions = [
'Story 1', 'Story 2'
]
this.handleQuestionChange = this.handleQuestionChange.bind(this);
this.storyOptionChange = this.storyOptionChange.bind(this);
}
handleTitleChange(e) {
console.log("Title is being updated");
this.setState({title: e.target.value});
}
storyOptionChange(e) {
}
getListOfStories() {
return this.storyOptions;
}
render() {
return (
<div className="StoryComponent">
<div>
<div>
<h3>Title</h3>
<input type="text" value={this.state.title} onChange={this.handleTitleChange} />
</div>
<div>
<Dropdown options={this.getListOfStories()} onChange={this.storyOptionChange} value={this.storyOptions[this.state.defaultStoryOption]} placeholder="Select a story" />
</div>
</div>
</div>
);
}
}
解决方案
最后想通了。诀窍是将标题作为数组存储在 App 中,然后将标题作为道具传递给 StoryComponent 中的下拉列表和输入字段。
handleTitleChange(e) {
console.log("Title is being updated");
this.setState({title: e.target.value});
}
变成...
handleTitleChange(e) {
console.log("Title is being updated");
this.props.onQuestionUpdate(e); // pass the value back up to App.
}
在应用程序里面我现在有......
private onQuestionUpdate(e:any) {
let storys = this.state.storys;
storys[Number(e.target.id)] = e.target.value;
this.setState({storys: storys});
}
推荐阅读
- c++ - 这些编译器之间有什么区别吗?
- ios - 如何设置 UNNotificationRequest 的自定义重复间隔?
- sql - SQL - varchar 列中的小数
- tfs - 如何从本地 TFS 2018.2 迁移到 DevOps 服务器
- ssis - 我想参数化与 Excel 文件的连接。但是文件的位置在sql server的一个表中。我怎样才能建立连接?
- php - 使用 PHP 脚本将 CSV 导入 MySQL
- optimization - 降低 CPU 频率的 SIMD 指令
- mongodb - MongoDB展开聚合查询给出意想不到的结果
- raspberry-pi - 树莓派中的node-red exec节点无法执行关机
- winforms - 根据其他控件留下的空间自动调整大小控件