繁体   English   中英

向CreatableSelect onClick in按钮添加新值以进行React-Select

[英]Adding new value to CreatableSelect onClick in button for React-Select

我正在尝试重现类似于SO的建议标签的内容,其中在单击时将建议标签添加到输入面板中。 然而,似乎CreatableSelect不会在重新初始化更新值value的道具。 难道我做错了什么?

这是我的codeandbox ,以便于参考。

index.js

  import React from "react"; import { render } from "react-dom"; import Suggestion from "./Suggestion"; import Form from "./Form"; class App extends React.Component { state = { options: [ { value: "Chocolate", label: "Chocolate" }, { value: "Strawberry", label: "Strawberry" }, { value: "Vanilla", label: "Vanilla" } ], stack: [{ value: "Bananna", label: "Bananna" }] }; // Issue here! // Adding "Mango" into the stack. Option does not show up in the select panel addToStack = name => { const { stack } = this.state; const length = Object.keys(stack).length; stack[length] = { value: name, label: name }; this.setState({ stack: stack }, () => { console.log("addToStack", stack); }); }; // Replacing new array from Selectable. Option shows up in the sekect panel replaceStack = arr => { var { stack } = this.state; stack = arr; this.setState({ stack: stack }, () => { console.log("replaceStack", stack); }); }; render() { const { options, stack } = this.state; return ( <div> <Form stack={stack} options={options} replaceStack={this.replaceStack} /> <br /> <Suggestion addToStack={this.addToStack} /> </div> ); } } render(<App />, document.getElementById("root")); 

Recommendation.js

 import React from "react"; class Suggestion extends React.Component { // Adds "Mango" by default handleClick = () => { this.props.addToStack("Mango"); }; render() { return ( <div> <button onClick={this.handleClick}> Add "Mango" into Select Panel </button> </div> ); } } export default Suggestion; 

Form.js

  import React from "react"; import CreatableSelect from "react-select/lib/Creatable"; class Form extends React.Component { handleChange = (arr, action) => { this.props.replaceStack(arr); }; render() { return ( <div> <CreatableSelect isMulti onChange={this.handleChange} options={this.props.options} value={this.props.stack} /> </div> ); } } export default Form; 

Here you go with the solution :  

https://codesandbox.io/s/w695qx2q7w

   addToStack = name => {
    console.log("addToStack", name);
    const { stack, options } = this.state;
    const newstack = { value: name, label: name };
    this.setState(
      { stack: [...stack, newstack], options: [...options, newstack] },
     () => {
       console.log("addToStack", this.state.stack);
       console.log("options", this.state.options);
    }
  )};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM