我知道在渲染过程中,我可以让孩子通过refs,例如,调用孩子的一个函数(我可以为此目的添加给孩子)来确定孩子的类型。
StringTokenizer st = new StringTokenizer(str);
int numofTokens = st.countTokens();
while( st.hasMoreElements() )
{
String TOKEN = st.nextToken();
for (int i = 0; i < reserved_Keywords.length; i++)
{
if ( TOKEN.equals(reserved_Keywords[i]) )
{
System.out.print(st.nextElement() + "\t");
System.out.println("Is Reserved Keyword");
}
}
但是在这个例子中,在装入Child之前实际上并没有调用该函数,所以在Parent的<Child ref={(child) => {this._childType = child.myFunctionToGetTheType();}} />
完成执行之后。
我有一个通过道具接收其子节点的父组件。因为React limitations我需要在父项的render
完成执行之前以特殊方式对待特定的孩子(即从父母的render
函数返回该特定孩子的其他内容)
是否可以在从父{q}}函数返回之前确定子类型(即不使用refs)?
答案 0 :(得分:4)
我有同样的问题,我依靠child.type.name
来确定组件的类型。虽然这对我来说很好,但问题是老浏览器不支持这种情况,所以我必须找到另一种方式。我使用无状态功能组件并且不想切换,所以最终利用了道具
const MySFC = () => {
//...
return (
<div className="MySFC"></div>
);
};
MySFC.propTypes = {
type: PropTypes.string
};
MySFC.defaultProps = {
type: "MySFC"
}
export default MySFC;
然后我使用child.type.name === 'MySFC'
child.props.type === 'MySFC'
不理想,但有效
答案 1 :(得分:0)
我在扩展React.Element的类中添加了一个静态函数,似乎我可以通过child.type.theStaticFunction
访问它。这可能仍然没有正确使用React API,但至少它在代码被缩小后起作用(child.type.name
不起作用,因为minifier正在用更短的版本替换类名)。
export default class MyType extends React.Component {
static isMyType() {
return true;
}
}
然后处理render
static _isChildOfMyType(child) {
const isMyType = child.type && child.type.isMyType && elem.type.isMyType();
return !!isMyType;
}