我目前正在开发一个React应用程序,其中有两个类-我们将其称为App类和Container类。基本上,App类具有一个状态数组,并且我想在此数组中包含许多Container对象。
class Container extends React.Component{
render(){
return(
<img src= {this.props.url} />
);
}
}
class App extends React.Component{
constructor(props){
super(props);
this.state = {
url: ""
data: []
}
}
handleSubmit(event){
event.preventDefault();
//I WANT TO BE ABLE TO MAKE A NEW CONTAINER, AND PASS THE URL AS PROPS.
// THEN, I WANT TO ADD THAT CONTAINER TO THE ARRAY.
this.setState({
data: url = this.state.url, id = 'a'
});
}
render(){
return (
<form onSubmit={this.handleSubmit}>
<label htmlFor="url">url:</label>
<input
type = "text"
name = "url"
value = {this.state.url}
onChange = {this.handleChange}
/>
</form>
)
}
}
在上述功能handleSubmit()中,我想向数组添加一个包含props URL的新容器。我该怎么办?
答案 0 :(得分:1)
url
处于状态,而不是整个容器setState
修改状态...
)进行串联handleChange
class Container extends React.Component {
render() {
return <img src={this.props.url} />;
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
url: "",
containers: []
};
}
handleChange = e => {
this.setState({
url: e.target.value
});
};
handleSubmit = event => {
event.preventDefault();
if (this.state.url) {
this.setState({
containers: [...this.state.containers, this.state.url],
url: ""
});
}
};
render() {
const { url, containers } = this.state;
return (
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="url">url:</label>
<input
type="text"
name="url"
value={url}
onChange={this.handleChange}
/>
<button>submit</button>
</form>
<h2>Containers:</h2>
<div>
{!containers.length && <i>no urls added</i>}
{containers.map((_url, i) => (
<Container key={i} url={_url} />
))}
</div>
</div>
);
}
}
render(<App />, document.getElementById("root"));