Javascript 从子组件修改父数组-反应
我正在构建一个React应用程序,我需要存储从该应用程序打开的所有窗口的处理程序(是的,这有点奇怪,但这是我必须做的)。在使用React之前,我将窗口存储在一个全局数组中,该数组与父窗口相连(我知道JS全局变量是一个非常糟糕的做法,但在项目中指定了这样做) 我不想使用Redux,只想用React解决这个问题。 在新的React应用程序中,我在应用程序组件的状态上声明了这个数组,并使用了一个方法来操作作为道具传递给子组件的stae:Javascript 从子组件修改父数组-反应,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我正在构建一个React应用程序,我需要存储从该应用程序打开的所有窗口的处理程序(是的,这有点奇怪,但这是我必须做的)。在使用React之前,我将窗口存储在一个全局数组中,该数组与父窗口相连(我知道JS全局变量是一个非常糟糕的做法,但在项目中指定了这样做) 我不想使用Redux,只想用React解决这个问题。 在新的React应用程序中,我在应用程序组件的状态上声明了这个数组,并使用了一个方法来操作作为道具传递给子组件的stae: class App extends Component {
class App extends Component {
constructor(props) {
super(props);
this.state = { name: 'Desktop', openedWindows: [] };
this.handleStateChange = this.handleStateChange.bind(this)
}
handleStateChange(param) {
this.setState({
openedWindows: [
...this.state.openedWindows,
param
]
})
}
render(){
常量主题=['#2c2f33',青色']
const backgroundColor=主题[0]
返回(
this.state.name===“桌面”?
:
)
}
}
导出默认应用程序;
这是试图更改状态的子组件:
class Landing extends Component {
handleOpenWindow = () => {
let newWindow = window.open('', '_blank')
this.props.handleStateChange= this.props.handleStateChange.bind(this)
}
render () {
const { backgroundColor } = this.props
return (
<div className='landing'>
<button className='btn'
onClick={this.handleOpenWindow}
style={{backgroundColor}}
>Abrir Editor
</button>
</div>
)
}
}
export default Landing
类着陆扩展组件{
handleOpenWindow=()=>{
让newWindow=window.open(“”,“\u blank”)
this.props.handleStateChange=this.props.handleStateChange.bind(this)
}
渲染(){
const{backgroundColor}=this.props
报税表(
Abrir编辑
)
}
}
导出默认着陆点
我得到一个TypeError:必须对函数调用Bind
我在函数调用上尝试了不同的方法,但我无法让它工作。不知道我做错了什么,或者不使用Redux是否可以做到这一点
感谢您的建议。有两个问题:
构造函数中有一个输入错误:this.handleStateChange.bind.bind(this)
这是一个.bind
太多了
在handleStateChange(param)
中,状态更新错误:
应该是
this.setState({
openedWindows: [
...this.state.openedWindows,
param
]
})
您必须在子组件的
handleOpenWindow()
中进行更改
handleOpenWindow = () => {
let newWindow = window.open('', '_blank')
this.props.handleStateChange(newWindow);
}
您必须将打开的窗口对象作为参数传递回父对象,并且不需要在此处绑定它。
Rest看起来不错。父组件
//创建状态为的数组
`constructor(props){
this.state={
name:[]
}
}`
现在创建一个函数,它接受数组作为参数并设置state
handleChange=(value)=>{
this.setState({name:value});
}
现在将函数作为道具传递给子组件,然后可以从子组件传递值(参数),最终在父组件中执行setState
`setData=()=>{
let name=[1,2,3,4];
this.props.handleChange(name);
}`
子组件
`setData=()=>{
let name=[1,2,3,4];
this.props.handleChange(name);
}`
确保将函数传递给子组件。
这将帮助您从子组件设置父组件中的状态。是
This.handleStateChange=This.handleStateChange.bind.bind(This)
复制粘贴错误?这是一个打字错误,我正在修改和编辑您不需要的帖子This.props.handleStateChange=This.props.handleStateChange.bind(This)
。只需调用this.props.handleStateChange(newWindow)
我更改了它,但现在我得到了TypeError:无法读取登录
组件中未定义的属性“bind”,您不必绑定它。只需分配onClick={this.props.handleStateChange}