我希望我的Button组件仅在将回调函数传递给该组件时才处理onClick
事件。我有两种解决方法,但我不知道哪种方法更好。
方法1 -在构造函数中将handleClick
与this.handleClick
或false
绑定,并将handleClick
传递给onClick
渲染方法。
class Button extends Component {
static propTypes = {
children: PropTypes.element.isRequired,
onClick: PropTypes.func
};
static defaultProps = {
onClick: undefined
};
constructor(props) {
super(props);
this.handleClick = (props.onClick) && this.handleClick.bind(this);
}
handleClick() {
const { onClick } = this.props;
onClick();
}
render() {
const { children } = this.props;
return (
<Wrapper onClick={this.handleClick}> // False if onClick is undefined
{children}
</Wrapper>
);
}
}
方法2 -在构造函数中绑定handleClick
,并在render方法中传递handleClick
或false
。
class Button extends Component {
static propTypes = {
children: PropTypes.element.isRequired,
onClick: PropTypes.func
};
static defaultProps = {
onClick: undefined
};
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
const { onClick } = this.props;
onClick();
}
render() {
const { children, onClick } = this.props;
return (
<Wrapper onClick={(onClick) && this.handleClick}>
{children}
</Wrapper>
);
}
}
答案 0 :(得分:1)
我认为这是一个偏好问题,因为两种情况几乎相等。
如果选择方法1 ,则会(有条件地)在内存中节省空间 ,因为在以下情况下,this.handleClick
的值很小props.onClick
是undefined
或false
,在第二种方法中,您将始终设置需要占用更多空间的函数(但是,该空间对于我)。
方法2 更常用,人们通常在没有任何条件的情况下将函数绑定到构造函数中,并在需要的属性中验证调用。
请注意,您可以使用第三种方法来使用onClick
道具中的define an arrow function,我并没有真正使用它,只是想提一下