反应从输入字段填充下拉列表

时间:2018-06-29 17:50:16

标签: javascript reactjs input dropdown

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

1 个答案:

答案 0 :(得分:0)

最后弄清楚了。技巧是将标题作为数组存储在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.
}

在App内部,我现在有...

private onQuestionUpdate(e:any) {
    let storys = this.state.storys;
    storys[Number(e.target.id)] = e.target.value;
    this.setState({storys: storys});
}