[英]How to create an object from another class, and push it into the state array?
I'm currently working on a React application, where I two classes - let's call them class App and class Container.我目前正在开发一个 React 应用程序,其中有两个类 - 我们称它们为类 App 和类 Container。 Basically, class App has a state array, and I want to have many Container objects in this array.
基本上,类 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>
)
}
}
In the function handleSubmit() above, I want to add a new container containing the props URL to the array.在上面的函数 handleSubmit() 中,我想向数组添加一个包含 props URL 的新容器。 How would I do this?
我该怎么做?
url
in the state, not the whole containerurl
,而不是整个容器setState
to modify the statesetState
修改状态...
) for concatenation...
) 进行连接handleChange
in your codehandleChange
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"));
Working Example: https://stackblitz.com/edit/react-g72uej工作示例: https : //stackblitz.com/edit/react-g72uej
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.