在子组件中,我使用onChange设置输入:
<input onChange={this.handlePlaylistTermChange} defaultValue={'New Playlist'}/>
然后设置用户输入内容的状态
handlePlaylistTermChange(e){
this.setState({playlistName: e.target.value });
然后,当单击按钮时,我将该值传递给一个方法,该方法使用props调用在单击按钮时处于该状态的父类方法
save() {
if (this.state.playlistName === null || this.state.playlistName === "") {
this.props.onSave('New Playlist') ;
} else {
this.props.onSave(this.state.playlistName);
}
}
它调用父类:
savePlaylist(name) {
let trackUrIs = [];
console.log(name);
let playlist =this.state.playlistTracks;
playlist.forEach(track =>{
trackUrIs.push(track.URI);
});
console.log( "passed in name"+ name);
console.log(trackUrIs);
Spotify.savePlaylist(trackUrIs,name);
console.log('whats happening here?' + this.state.playlistName);
this.setState({playlistTracks: []});
this.setState({playlistName: ''});
这一切都很好,除了我需要将播放列表名称值更改回“新播放列表”,但是无论我做什么,onChange上发生的值仍然存在。我尝试过重置孩子的状态并将其传递给父母,无论单击保存按钮后,无论如何我都无法将onchange值重置为“新播放列表”。
答案 0 :(得分:1)
DefaultValue
仅在安装时分配给输入,并且不能进行更改而进行更新,您应该使用 controlled input
并根据以下内容设置值状态并为了定义defaultValue
,请在state
state={
playList: 'New Playlist'
}
<input onChange={this.handlePlaylistTermChange} value={this.state.playList}/>
现在输入字段onChange
中,您可以更新playList状态以反映输入中的更新值
handlePlaylistTermChange =(e) => {
this.setState({playList: e.target.value});
}
答案 1 :(得分:0)
constructor(props) {
super(props);
this.state = { clickedItem: "show here..." };
this.ItemClick = this.ItemClick .bind(this);
}
ItemClick = (e) => {
this.setState({ clickedItem: e.target.value});
}