Javascript 如何在reactjs中使用高阶组件添加按钮
如何使用高阶组件向组件添加按钮?我试过了,但没有在组件中添加按钮。它是在原始组件之前添加它Javascript 如何在reactjs中使用高阶组件添加按钮,javascript,reactjs,Javascript,Reactjs,如何使用高阶组件向组件添加按钮?我试过了,但没有在组件中添加按钮。它是在原始组件之前添加它 const withButton = WrappedComponent => { return class extends Component { render() { return ( <Fragment> <button>BUTTON ADDED USING HOC</button>
const withButton = WrappedComponent => {
return class extends Component {
render() {
return (
<Fragment>
<button>BUTTON ADDED USING HOC</button>
<WrappedComponent {...this.props} />
</Fragment>
)
}
}
}
export default withButton
ComponentWithButton添加了button,但它是在WrappedComponent之前添加的,而我希望将button作为WrappedComponent的子级添加到内部
假设WrappedComponent呈现如下内容
<div className="baseClass">{other divs and layout}</div>
{其他分区和布局}
常量ComponentWithButton=withButton(WrappedComponent)
ComponentWithButton应呈现以下内容
<div className="baseClass">
<button>BUTTON ADDED USING HOC</button>
{other divs and layout}
</div>
使用HOC添加的按钮
{其他分区和布局}
如果要动态地将按钮放置在WrappedComponent中的某个位置,可以尝试以下方法
const withButton = WrappedComponent => {
return class extends Component {
render() {
return (
<Fragment>
<WrappedComponent {...this.props}>
<button>BUTTON ADDED USING HOC</button>
</WrappedCompnent>
</Fragment>
)
}
}
}
export default withButton
constwithbutton=WrappedComponent=>{
返回类扩展组件{
render(){
返回(
使用HOC添加的按钮
)
}
}
}
使用按钮导出默认值
现在,在WrappedComponent中,您可以将按钮放置在任何您想要的位置,因为按钮可以作为WrappedComponent的子属性进行访问
const WrappedComponent = ({ children, ...otherProps }) => (
<div className="baseClass">
{children}
{renderOtherDivsAndProps(otherProps)}
</div>
);
constwrappedcomponent=({children,…otherProps})=>(
{儿童}
{renderOtherDivsAndProps(其他props)}
);
希望这有助于您尝试使用,也请参考
函数组件WithButton({children}){
返回(
使用HOC添加的按钮
{儿童}
);
}
然后渲染:
课程:
class ComponentWithButton扩展组件{
render(){
const{children}=this.props;
返回(
使用HOC添加的按钮
{儿童}
);
}
}
导出默认组件WithButton;
我尝试了这个,我得到了我想要的东西
constwithbutton=WrappedComponent=>{
返回类扩展组件{
render(){
返回(
使用HOC添加的按钮
{this.props.children}
)
}
}
}
使用按钮导出默认值
请澄清“内部”是什么意思。小时候?WrappedComponent自己的孩子会怎么样?请为WrappedComponent添加一个示例,以及您希望withButton如何修改布局。嗨,estus,是的,我希望将button作为子项添加到包装组件中。包装组件已经有了基本的样式,我只想添加按钮,必要时它也将是包装组件的一部分。您是否尝试将按钮放在包装组件内?使用HOC添加的按钮这仍然取决于WrappedComponent。…
做你想做的事吗?请提供一个例子,以防它没有。如果我添加按钮内,将只有按钮的一面
const WrappedComponent = ({ children, ...otherProps }) => (
<div className="baseClass">
{children}
{renderOtherDivsAndProps(otherProps)}
</div>
);