【问题标题】:React Select - setState of propReact Select - 属性的 setState
【发布时间】:2016-07-25 16:18:57
【问题描述】:

我正在尝试使用React Select 在 ReactJS 中设置我的 brandSelect 道具的状态,但是我对如何做到这一点感到困惑?

这是我当前的代码:

class VehicleSelect extends React.Component {

  constructor(props) {
    super(props);

    this.state = { brandSelect: ""};

  }
  render() {
    var options = [
    { value: 'Volkswagen', label: 'Volkswagen' },
    { value: 'Seat', label: 'Seat' }
    ];


    return (
      <Select
          name="form-field-name"
          value={this.state.brandSelect}
          options={options}
          placeholder="Select a brand"
          searchable={false}
          onChange={}
      />
    )
  }
};

选择选项时,我希望将状态设置为选项。

有没有人知道 React Select 是如何做到这一点的,因为文档并没有真正涵盖这一点?到目前为止,我已经尝试制作一个附加到 onChange 道具的设置状态的函数,但这不起作用。

【问题讨论】:

    标签: javascript reactjs react-select


    【解决方案1】:

    在 react 16.8+ 中,使用 React hooks 的实现应该如下所示:

    Hooks 是 React 16.8 中的新增功能

    function VehicleSelect() {
    
      const options = [
        { value: 'volkswagen', label: 'Volkswagen' },
        { value: 'seat', label: 'Seat' }
      ];
    
      const [selectedOption, setSelectedOption] = useState({ value: 'volkswagen', label: 'Volkswagen' });
    
      const [handleChange] = useState(() => {
        return () => {
          setSelectedOption(selectedOption);
        };
      });
    
      return (
        <div className="App">
          <Select
            name="form-field-name"
            placeholder="Select a brand"
            searchable={false}
            value={selectedOption}
            onChange={handleChange}
            options={options}
          />
        </div>
      );
    }
    

    【讨论】:

      【解决方案2】:

      您可以尝试将_onChange 处理程序添加到您的组件,它将处理来自&lt;Select /&gt; 组件的更改。

      class VehicleSelect extends React.Component {
      
        constructor(props) {
          super(props);
      
          this.state = { brandSelect: ""};
      
        }
      
        _onChange(value) {
          //console.log(value) - just to see what we recive from <Select />
          this.setState({brandSelect: value});
        }
      
        render() {
          var options = [
          { value: 'Volkswagen', label: 'Volkswagen' },
          { value: 'Seat', label: 'Seat' }
          ];
      
      
          return (
            <Select
                name="form-field-name"
                value={this.state.brandSelect}
                options={options}
                placeholder="Select a brand"
                searchable={false}
                onChange={this._onChange.bind(this)}
            />
          )
        }
      };
      

      【讨论】:

        【解决方案3】:

        试试这个:

        class VehicleSelect extends React.Component {
        
            constructor(props) {
              super(props);
        
              this.state = {
                brandSelect: ""
              };
        
            }
            onSelectChanged(value) {
              this.setState({
                brandSelect: value
              });
            }
            render() {
                var options = [{
                  value: 'Volkswagen',
                  label: 'Volkswagen'
                }, {
                  value: 'Seat',
                  label: 'Seat'
                }];
        
                <Select
               name="form-field-name"
               value={this.state.brandSelect}
               options={options}
               placeholder="Select a brand"
               searchable={false}
               onChange={this.onSelectChanged.bind(this)}
               />
        

        您需要一个onChange 事件处理程序。将参数传递给事件处理函数,在这种情况下,该参数将是 Select 输入的选定值,然后使用选定值设置brandSelect 的状态

        【讨论】:

          【解决方案4】:

          我在我的代码中使用了它来使用 Selector:

          class VehicleSelect extends React.Component {
          
            constructor(props) {
              super(props);
          
              this.state = { brandSelect: ""};
          
            }
          
            onChange(event) {
              this.setState({brandSelect: event.target.value}); // important
            }
          
            render() {
              var options = [
              { value: 'Volkswagen', label: 'Volkswagen' },
              { value: 'Seat', label: 'Seat' }
              ];
          
          
              return (
                <Select
                    name="form-field-name"
                    value={this.state.brandSelect}
                    options={options}
                    placeholder="Select a brand"
                    searchable={false}
                    onChange={this.onChange.bind(this)}
                />
              )
            }
          };
          

          【讨论】:

            【解决方案5】:
            const Layout = (props: any) => {
            
            //Row First
            const [rows, setRow] = useState({
                rowFirst: "",
                columnFirst: "",
                columnSecond: 0
            });
            
            const handleChangeRowFirst = (e: { target: { name: any; value: any; }; }) => {
            
            
                setRow({ ...rows, [e.target.name]: e.target.value });
            
                console.log("row", rows);
            
                props.dispatch({
                    type: "setRow",
                    payload: rows
                });
            
            };
            
            const onSubmitForm = (e: any) => {
                e.preventDefault();
                if (!rows.rowFirst) {
                    alert("rowFirst is empty.")
                }
                else if (!rows.columnFirst) {
                    alert("columnFirst or rowFirst is empty.")
                }
                else if (!rows.columnSecond) {
                    alert("columnSecond is empty.")
                }
            }
            
            
            
            return (
                <>
                    <Grid container className="containerMatrix">
                        <form onSubmit={onSubmitForm} className="formMatrix">
                            <Grid item xs={6} md={5}>
                                <Box id="test" className="martixNum">
                                    <Typography variant="h5" gutterBottom className="nameColMatrix">
                                        Enter Numbers First Matrix
                                    </Typography>
            
                                    <Box className="martixFirst">
                                        <TextField
                                            type="number"
                                            InputProps={{
                                                inputProps: {
                                                    max: 99, min: 0
                                                }
                                            }}
                                            label="Row" onChange={handleChangeRowFirst} name="rowFirst" id="num1" value={rows.rowFirst}
                                        />
                                        <TextField
                                            type="number"
                                            InputProps={{
                                                inputProps: {
                                                    max: 99, min: 0
                                                }
                                            }}
                                            label="Column" onChange={handleChangeRowFirst} name="columnFirst" id="num2" value={rows.columnFirst}
                                        />
                                    </Box>
                                </Box>
                            </Grid>
            
                            <Grid item xs={6} md={5}>
                                <Box id="test" className="martixNum">
                                    <Typography variant="h5" gutterBottom className="nameColMatrix">
                                        Enter Numbers Second Matrix
                                    </Typography>
                                    <Box className="martixFirst">
                                        <TextField
                                            type="number"
                                            InputProps={{
                                                inputProps: {
                                                    max: 99, min: 0
                                                }
                                            }}
                                            label="Row" onChange={handleChangeRowFirst} name="columnFirst" id="num3" value={rows.columnFirst}
                                        />
            
                                        <TextField
                                            type="number"
                                            InputProps={{
                                                inputProps: {
                                                    max: 99, min: 0
                                                }
                                            }}
                                            label="Column" onChange={handleChangeRowFirst} name="columnSecond" id="num4"
                                        />
                                    </Box>
            
                                </Box>
                            </Grid>
                            <Grid item xs={6} md={5}>
                                <Box>
                                    <Button variant="contained" color="primary" type="submit">
                                        Primary
                                    </Button>
                                </Box>
                            </Grid>
                        </form>
                    </Grid>
                </>
            )
            }
            

            【讨论】:

            • 请解释您的解决方案。没有解释且只有代码的答案会被标记为低工作量。
            • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
            猜你喜欢
            • 2017-11-04
            • 2020-01-16
            • 2017-09-24
            • 2019-04-09
            • 2018-12-05
            • 2016-03-03
            • 1970-01-01
            • 2020-07-10
            • 1970-01-01
            相关资源
            最近更新 更多