我想从app.js控制子组件中的所有状态。因为当我将状态对象发布到API时,我希望发送所有更改。
import React, {Component} from 'react'
import Navigation from './navigation'
import View from './view'
class App extends Component {
constructor(props) {
super(props)
this.state = {
all: {}
}
}
render() {
return (
<div>
<div className="app">
<Navigation />
<div className="editable">
{this.props.children}
</div>
<View />
</div>
</div>
)
}
}
export default App
其他组件正在与路由器连接。所以我想从root children数据中填写this.state.all。
这是根组件之一
import React, {Component} from 'react'
class Image extends Component {
constructor(props) {
super(props)
this.state = {
imageWidthBar: 64,
imageHeightBar: 64
}
this.handleInput = this.handleInput.bind(this)
}
handleInput(event) {
this.setState({
[event.target.name]: event.target.value
})
}
render() {
return (
<div className="block">
<div className="block__row">
<span>Image Width</span>
<input type="number" name="imageWidthBar" value={this.state.imageWidthBar} onChange={this.handleInput} />
<input type="range" name="imageWidthBar" min="0" max="240" step="16" value={this.state.imageWidthBar} onChange={this.handleInput} />
</div>
<div className="block__row">
<span>Image Height</span>
<input type="number" name="imageHeightBar" value={this.state.imageHeightBar} onChange={this.handleInput} />
<input type="range" name="imageHeightBar" min="0" max="240" step="16" value={this.state.imageHeightBar} onChange={this.handleInput} />
</div>
</div>
)
}
}
export default Image
你建议我做什么?
答案 0 :(得分:0)
...
handleImageData(data){
this.setState({ all: data })
}
...
<div className="editable">
{React.cloneElement(this.props.children, {
handleImageData: this.props.handleImageData.bind(this)
})}
</div>
在儿童
handleInput(event) {
this.setState({
[event.target.name]: event.target.value
})
this.props.handleImageData(event.target.value)
}
但它不是最正确的解决方案,因为您将此道具发送给您的所有子组件。对于这项任务,我觉得最好使用redux中的商店
同时检查this