首页 > 解决方案 > 反应从输入字段填充下拉列表

问题描述

我有一个简单的 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>
        );
    }
}

标签: javascriptreactjsinputdropdown

解决方案


最后想通了。诀窍是将标题作为数组存储在 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});
}

推荐阅读