我有一个项目可以添加,编辑或删除列表中的电影。我在组件的编辑部分遇到问题,在每部电影旁边我添加了一个文本输入来编辑该电影,如果需要,但我不知道如何将该值传递给其他组件的顺序更改新值的旧值。这是我现在得到的: 电影组件:
import React, {Component} from 'react';
class Movie extends Component{
constructor(props){
super(props);
this.state= {
inputValue: ''
};
}
updateInputValue(evt) {
this.setState({
inputValue: evt.target.value
});
}
render(){
return(
<div>
{this.props.text}
<button onClick={this.props.deleteMethod}>X</button>
<input value={this.props.newMovieName}
onChange={evt => this.updateInputValue(evt)}
/>
<button onClick={this.props.editMethod().bind(this.inputValue)}>edit</button>
</div>
);
}
}
export default Movie;
添加组件:
import React,{Component} from 'react';
import Movie from './Movie.jsx';
class AddComponent extends Component {
constructor(props){
super(props);
this.state = {
movieText: '',
movies: [],
};
}
updateMovieText(movieText){
this.setState({movieText: movieText.target.value})
}
addMovie(){
if(this.state.movieText === ''){return}
let moviesArr = this.state.movies;
moviesArr.push(this.state.movieText);
this.setState({movieText: ''})
this.textInput.focus();
}
handleKeyPress = (event) => {//enables to add when pressing enter on keyboard
if(event.key === 'Enter'){
let moviesArr = this.state.movies;
moviesArr.push(this.state.movieText);
this.setState({movieText: ''})
}
}
deleteMovie(index) {
let movieArr = this.state.movies;
movieArr.splice(index,1);//remove the movie from array
this.setState({movies: movieArr})
}
editMovie(index,value){
let moviesArr = this.state.movies;
moviesArr[index] = value;
this.setState({movies:movieArr});
}
render(){
let movie = this.state.movies.map((val,key)=> {//prints on screen list of movies see line55
return (<Movie
key={key}
text={val}
deleteMethod={() => this.deleteMovie(key)}
editMethod={() => this.editMovie(key,this.inputValue)}
/>
);
});
return (
<div>
<input type="text"
ref={((input)=>{this.textInput = input;})}
className="textInput"
value={this.state.movieText}
onChange={movieText => this.updateMovieText(movieText)}
onKeyPress={this.handleKeyPress.bind(this)}
/>
<button onClick={this.addMovie.bind(this)}>Add</button>
{movie}
</div>
);
}
}
export default AddComponent;
我认为我应该使用bind,但现在它还没有工作
答案 0 :(得分:1)
您需要绑定AddComponent
中的密钥,以便识别正在编辑的电影,例如
let movie = this.state.movies.map((val,key)=> {
return (<Movie
key={key}
text={val}
deleteMethod={() => this.deleteMovie(key)}
editMethod={this.editMovie.bind(this, key)}
/>
);
然后在Movie
组件中,您需要在点击时传递最新的输入值,例如
<button onClick={() => this.props.editMethod(this.state.inputValue)}>edit</button>