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

javascript - ReactJS Select Key - Stack Overflow

programmeradmin14浏览0评论

I have a Select that get's values from API, then on change it gets the value from the select and renders a table. but I want the select to display planet.id and planet.name, but doing it using event.target.value wont work since it would pass both values and table wouldn't render! Any way of doing this passing for example key={planet.id}?

class Planet extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: 1};
       
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event){
        this.setState({value: event.target.value});
    }

    render () {

        let planets = this.props.state.planets;
        let optionItems = planets.map((planet) =>
                <option key={planet.id} >{planet.id}</option>
            );

I have a Select that get's values from API, then on change it gets the value from the select and renders a table. but I want the select to display planet.id and planet.name, but doing it using event.target.value wont work since it would pass both values and table wouldn't render! Any way of doing this passing for example key={planet.id}?

class Planet extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: 1};
       
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event){
        this.setState({value: event.target.value});
    }

    render () {

        let planets = this.props.state.planets;
        let optionItems = planets.map((planet) =>
                <option key={planet.id} >{planet.id}</option>
            );

Share Improve this question edited Oct 10, 2019 at 9:17 Vadim Kotov 8,2848 gold badges50 silver badges63 bronze badges asked May 11, 2018 at 11:04 zemmsoareszemmsoares 3531 gold badge8 silver badges28 bronze badges 4
  • where is value property in <option> tag? – Raviteja Commented May 11, 2018 at 11:08
  • add value property to <option>. – Amanshu Kataria Commented May 11, 2018 at 11:09
  • @Raviteja after adding a value={planet.id} made it work, but strangely it was working without the value property? – zemmsoares Commented May 11, 2018 at 11:12
  • You'll able to select any option. To save the selected option you need value – Raviteja Commented May 11, 2018 at 11:15
Add a ment  | 

2 Answers 2

Reset to default 3

You mean this?:

<option key={planet.id} value={planet.id} >{planet.id}-{planet.name}</option>

Try this

<option key={planet.id} value={planet.id}>{planet.name}</option>
发布评论

评论列表(0)

  1. 暂无评论