Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 访问子组件内的函数参数_Javascript_Reactjs_Function - Fatal编程技术网

Javascript 访问子组件内的函数参数

Javascript 访问子组件内的函数参数,javascript,reactjs,function,Javascript,Reactjs,Function,我有一段我正在编写的代码- <ChildComponent OnSelect={() => this.changeEntity(index)} /> this.changeEntity(索引)}/> 我需要访问ChildComponent中的“index”值。如果需要访问index的值,请传递该值 你不能把它从函数中拉出来 <ChildComponent index={index} OnSelect={() => this.changeEntity(index)

我有一段我正在编写的代码-

<ChildComponent OnSelect={() => this.changeEntity(index)} />
this.changeEntity(索引)}/>

我需要访问ChildComponent中的“index”值。

如果需要访问
index的值,请传递该值

你不能把它从函数中拉出来

<ChildComponent index={index} OnSelect={() => this.changeEntity(index)} />
this.changeEntity(索引)}/>

我假设ChildComponent本身有一个独立于父组件的索引值。在这种情况下,可以将函数作为prop传递给子函数

<ChildComponent OnSelect={this.changeEntity} />

在子组件中:

constructor(props){
 //stores index maybe in the state     
 this.state = {
   index: 0 // or some other value
   ... 
 }
}

<SomeElement onSelect={() => this.props.changeEntity(index)} /> 
// here index is stored inside the ChildComponent independent of the parent component
构造函数(道具){
//存储索引可能在状态中
此.state={
索引:0//或其他一些值
... 
}
}
this.props.changeEntity(索引)}/>
//这里索引存储在子组件中,独立于父组件

我还假设您使用的是react。

请告诉我们这是否是一个足够的解决方案,或者您是否打算在调用OnSelect方法期间以某种方式告诉ChildComponent什么是
index
this.changeEntity(index)}index={index}/>
子组件是一个实用程序组件,因此我没有将索引作为道具传递。我想知道,如果不将其作为prop传递,是否可以做任何事情,为什么要“访问ChildComponent内部的索引……而不将其作为prop传递”?它“是一个实用组件”的理由并不能确切地告诉我你不把它作为道具传递进来想要避免什么。实际上,childcomponent在forEach内部,forEach的索引作为索引传递。所以我需要通过索引。是的,然后你可以通过索引作为一个propI。我想我现在必须这样做。谢谢你的帮助。如果你期待一个更好的解决方案,你能发布代码,也许我们能找到一个好的解决方案吗?