最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Select - setState of prop - Stack Overflow

programmeradmin0浏览0评论

I am trying to set the state of my brandSelect prop in ReactJS using React Select however I am confused to how this can be done?

Here is my current code:

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={}
      />
    )
  }
};

When the option is selected I want the state to be set as the option chosen.

Does anybody know how this is done with React Select as the documentation doesn't really cover this? So far I have tried making a function with a set state attached to the onChange prop however this didn't work.

I am trying to set the state of my brandSelect prop in ReactJS using React Select however I am confused to how this can be done?

Here is my current code:

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={}
      />
    )
  }
};

When the option is selected I want the state to be set as the option chosen.

Does anybody know how this is done with React Select as the documentation doesn't really cover this? So far I have tried making a function with a set state attached to the onChange prop however this didn't work.

Share Improve this question asked Jul 25, 2016 at 16:18 Nick MaddrenNick Maddren 5832 gold badges7 silver badges20 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 2

In react 16.8+ the implementation should look like this using React hooks:

Hooks are a new addition in 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>
  );
}

You can try do add _onChange handler to your ponent, that will handle changes form <Select /> ponent.

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)}
      />
    )
  }
};

Try this:

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)}
       />

You need an onChange event handler. Pass in an argument to the event handler function which in this case will be the selected value of the Select input and then Set the State of the brandSelect with the selected value.

I used this in my code to work with 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)}
      />
    )
  }
};
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>
    </>
)
}
发布评论

评论列表(0)

  1. 暂无评论