当前位置: 动力学知识库 > 问答 > 编程问答 >

meteor - onChange event doesn't change state in <select> React

问题描述:

As the title, I have an onChange event for the <select> element in React, but it doesn't fire when I change the option in the dropdown.

I set the initial state, update the state with this.setState() and test it with 2 onChange event, 1 for the text input, and the other for the <select>.

Only the state of the text input is updated. It means only the text input called the onChange event.

Can anyone help me figure out why this happens?

ServicesPage = React.createClass({

mixins: [ReactMeteorData],

getMeteorData() {

var accountId = Meteor.userId();

return {

services: Services.find({ accountId: accountId }).fetch(),

sites: Sites.find({ accountId: accountId }).fetch()

}

},

getInitialState() {

return {

selected: "0",

test: 'Hello'

}

},

handleChangeLocation(e) {

this.setState({ selected: e.target.value });

},

handleChange(event) {

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

console.log(this.state.test);

},

componentDidMount() {

$('select').material_select();

console.log(this.state.selected);

},

render() {

var sitesList = [];

for (var i = 0; i < this.data.sites.length; i++) {

sitesList.push(<option key={i} value={this.data.sites[i]._id}>{this.data.sites[i].name}</option>);

}

return (

<div>

<input type="text" value={this.state.test} onChange={this.handleChange} />

<h4>Services Page</h4>

<div className="row">

<div className="col s12 m6 l6">

<select value={this.state.selected} onChange={this.handleChangeLocation}>

<option value="0">Choose location</option>

{sitesList}

</select>

</div>

</div>

</div>

)

}

})

网友答案:

material_select inserts it's own DOM elements and hides the existing <select> hierarchy. The React elements don't know anything about this since they work only at the level of the virtual DOM. Therefore material_select undermines the connection between the React virtual DOM and the real DOM.

This will be the case for almost all JQuery plugins, so they are mostly incompatible with React. You probably want to use the material-ui React components instead.

分享给朋友:
您可能感兴趣的文章:
随机阅读: