React.js使用props将值发送给后代组件错误?
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions, RequestMethod, Request } from '@angular/http';
import { Observable } from 'rxjs/Observable';
// import { Network } from 'ionic-native';
import { Network } from '@ionic-native/network';
@Injectable()
export class CustomHttpService {
//other code
public connection = () => {
return Network.type;
}
public onDisconnect = ():Observable<any> => {
return Network.onDisconnect();
}
public onConnect = ():Observable<any> => {
return Network.onConnect();
}
}
我编写了之前的演示来测试使用const Child = props => <div onClick={ e => console.log(props.value) }>Click to see value.</div>
const Father = props => <div>{ React.cloneElement(props.children, props) }</div>
const GrandFather = props => <div>{ React.cloneElement(props.children, props) }</div>
ReactDOM.render(
<GrandFather value="This is Test">
<Father>
<Child />
</Father>
</GrandFather>,
document.getElementById('root')
)
向后代组件发送信息。但它导致了错误:
Uncaught RangeError:Object.ReactElement.cloneElement
超出了最大调用堆栈大小
但是我在演示运行之后写的很好,所以你能告诉我导致错误的原因吗?
props
答案 0 :(得分:0)
您必须只克隆一个元素。 React.Children是一个数组
https://facebook.github.io/react/docs/react-api.html#cloneelement
React.cloneElement(
element,
[props],
[...children]
)
答案 1 :(得分:0)
我在经过一些测试后解决了这个问题。
首先,我将问题放在Father
组件中。
其次,错误的信息Maximum call stack size exceeded
总是由无限创造而不回收的东西引起的。
所以,我发现道具 我发送给Father
的值children
本身就是 - Father
。< / p>
GrandFather
有道具:
{
value: "This is Test",
children: Father React Element
}
当我使用React.cloneElement(child, props)
时,the props.children = Father React Element
也会发送到父组件。
检查React API后,.cloneElement
的第三个参数是克隆元素的children
。
总之,我的解决方案是:
const Father = props => <div>{ React.Children.map(props.children, child => React.cloneElement(child, props, child.props.children)) }</div>
整个演示都在:
const CloneProps2Children = props => <div>{ React.Children.map(props.children, child => React.cloneElement(child, props, child.props.children)) }</div>
const Child = props => <div onClick={ e => console.log(props.value) }>Click to see value.</div>
export default (
<CloneProps2Children value="This is test for many middles">
<CloneProps2Children>
<CloneProps2Children>
<Child></Child>
</CloneProps2Children>
</CloneProps2Children>
</CloneProps2Children>
)