我有问题。我想在React的datalist标签上处理onClick事件。我有自动建议的输入。输入几个字母后,将显示一个带有建议的数据列表。我想将数据列表中的选定值传递给方法
getClickedCityHandler = receivedData => {
this.setState({ inputCity: receivedData.name });
console.log(this.state.inputCity.length);
this.setState({ passedCity: receivedData });
};
这是我的代码组件:
import React from "react";
import { connect } from "react-redux";
import styles from "./AddCity.module.scss";
import * as actions from "../../store/actions/index";
class AddCity extends React.Component {
state = {
inputCity: "",
filteredCities: [],
passedCity: {}
};
componentDidMount() {
this.props.getCities();
}
cityTypeHandler = event => {
this.setState({ inputCity: event.target.value });
this.setState({
filteredCities: this.props.listOfCities.filter(el =>
el.name.includes(event.target.value)
)
});
};
getClickedCityHandler = receivedData => {
this.setState({ inputCity: receivedData.name });
console.log(this.state.inputCity.length);
this.setState({ passedCity: receivedData });
};
render() {
const listOfCities = this.props.listOfCities.map(el => (
<option
value={el.name}
onClick={() => this.getClickedCityHandler(el)}
key={el.id}
/>
));
return (
<>
<div className={styles.InputContainer}>
<input
className={styles.CityInput}
placeholder="City"
value={this.state.inputCity || ""}
onChange={this.cityTypeHandler}
ref={input => (this.search = input)}
list="cities"
/>
<button
className={styles.AddCityButton}
onClick={() =>
this.props.onCityAdd(this.state.passedCity)}
/>
</div>
{this.state.inputCity.length > 2 && this.state.inputCity ? (
<datalist
onChange={() =>
this.getClickedCityHandler(this.state.inputCity)}
id="cities"
>
{listOfCities}
</datalist>
) : null}
</>
);
}
}
const mapStateToProps = state => {
return { listOfCities: state.list.citiesLoaded };
};
const mapDispatchToProps = dispatch => {
return {
onCityAdd: city => {
dispatch(actions.getCityInfo(city));
},
getCities: () => dispatch(actions.getData())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(AddCity);
在数据列表中单击选项后,没有任何反应。我尝试使用数据列表和选项上的onChange和onClick事件。