我怎样才能通过捷径控制道具?
How can i control props by the short way?
我想知道我们怎样才能让这个案例变得简单?
我有一个自定义的 Typeahead 组件,这将执行我自定义的一些操作。所以我想通过 TypeaheadCustom 组件的 props 来控制 Typeahead 的 props:
在我调用 TypeaheadCustom 的组件中:
<TypeaheadCustom propsControler />
在 TypeaheadCustom 组件中:
function TypeaheadCustom({ propsControler ,children, ...otherProps }, ref) {
if(propsControler=== true) { //make some propsOfTypeahead}
return (
<Fragment>
<Typeahead ref={ref} {...otherProps} //propsOfTypeahead>
{children}
</Typeahead>
</Fragment>
);
}
}
我想这样做,因为我希望它干净。我们怎样才能做到这一点?谢谢
你可以为此写一个HoC。在 HoC 中,您传递 propsControler。如果为真,则 return 组件否则 return 为空。这是伪代码
`
function TypeaheadCustom(propsControler, childrenComponent, ref) {
return propsControler === true ? (<Fragment>
<Typeahead ref={ref} {...otherProps}> //propsOfTypeahead>
{<childrenComponent />} // It shall have the props of its own
</Typeahead>
</Fragment>) : null
}
}
`
您可以在条件内创建对象,并将该对象作为道具传递
function TypeaheadCustom({ propsControler ,children, ...otherProps }, ref) {
if(propsControler=== true) {
const propsOfTypeahead = {prop1: 1, prop2: 2}
return (
<Fragment>
<Typeahead ref={ref} {...otherProps} {...propsOfTypeahead}>
{children}
</Typeahead>
</Fragment>
);
}
}
我想知道我们怎样才能让这个案例变得简单?
我有一个自定义的 Typeahead 组件,这将执行我自定义的一些操作。所以我想通过 TypeaheadCustom 组件的 props 来控制 Typeahead 的 props:
在我调用 TypeaheadCustom 的组件中:
<TypeaheadCustom propsControler />
在 TypeaheadCustom 组件中:
function TypeaheadCustom({ propsControler ,children, ...otherProps }, ref) {
if(propsControler=== true) { //make some propsOfTypeahead}
return (
<Fragment>
<Typeahead ref={ref} {...otherProps} //propsOfTypeahead>
{children}
</Typeahead>
</Fragment>
);
}
}
我想这样做,因为我希望它干净。我们怎样才能做到这一点?谢谢
你可以为此写一个HoC。在 HoC 中,您传递 propsControler。如果为真,则 return 组件否则 return 为空。这是伪代码
`
function TypeaheadCustom(propsControler, childrenComponent, ref) {
return propsControler === true ? (<Fragment>
<Typeahead ref={ref} {...otherProps}> //propsOfTypeahead>
{<childrenComponent />} // It shall have the props of its own
</Typeahead>
</Fragment>) : null
}
}
`
您可以在条件内创建对象,并将该对象作为道具传递
function TypeaheadCustom({ propsControler ,children, ...otherProps }, ref) {
if(propsControler=== true) {
const propsOfTypeahead = {prop1: 1, prop2: 2}
return (
<Fragment>
<Typeahead ref={ref} {...otherProps} {...propsOfTypeahead}>
{children}
</Typeahead>
</Fragment>
);
}
}