可以更改 onclick 函数,例如更改 props,例如更改'props message'
to 'new message'
?
例如:
var SmallMessageBox = React.createClass({
getDefaultProps: function() {
return {
message: 'props message',
onClick: 'this.eventHandler_Two'
}
},
eventHandler_One: function(){
console.log('event1');
},
eventHandler_Two: function(){
console.log('event2');
},
render: function(){
return (
<div>
<small>{this.props.message}</small>
<button onClick={this.eventHandler_One}>button</button>
</div>
);
}
});
React.render(
<SmallMessageBox message="new message" onClick="new onClick function for event2" />, document.getElementById('react-container'),
function(){
console.log('after render');
}
);
是的,组件可以提供函数类型的属性。您可以将事件处理程序直接绑定到通过 props 传递的函数,或者在执行 prop 函数之前在内部组件方法中执行某些操作。请注意,您无法更改所提供函数的定义,一旦目标组件被初始化,它将不会被更新。
此外,在许多情况下,您必须在传入的函数上使用绑定以维护正确的上下文。
根据您的示例,它应该如下所示:
var SmallMessageBox = React.createClass({
propTypes: {
message: React.PropTypes.string.isRequired,
onClick: React.PropTypes.func
},
getDefaultProps: function() {
return {
message: 'props message',
onClick: function() {
console.log("I will be executed, only if props.onClick was not specified");
}
}
},
eventHandler: function() {
},
render: function() {
return (
<div>
<small>{this.props.message}</small>
<button onClick={ this.props.onClick }>button</button>
</div>
);
}
});
React.render(
<SmallMessageBox onClick={function() { console.log( "remove me to get the other console.log"); }} message="new message"/>, document.getElementById('react-container'),
function(){
console.log('after render');
}
);
我还鼓励您隐式指定道具的类型。您可以找到更多信息here https://facebook.github.io/react/docs/reusable-components.html.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)