react 事件
Posted 天行子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了react 事件相关的知识,希望对你有一定的参考价值。
<div id="example"></div>
<script type="text/babel">
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 这边绑定是必要的,这样 `this` 才能在回调函数中使用
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? \'ON\' : \'OFF\'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById(\'example\')
);
</script>
<div id="root"></div>
<script type="text/babel">
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
function LoginButton(props) {
return (
<button onClick={props.onClick}>
Login
</button>
);
}
function LogoutButton(props) {
return (
<button onClick={props.onClick}>
Logout
</button>
);
}
class LoginControl extends React.Component{
constructor(props){
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {isLoggedIn:false}
}
handleLoginClick(){
this.setState({isLoggedIn:true});
}
handleLogoutClick(){
this.setState({isLoggedIn:false});
}
render(){
const isLoggedIn = this.state.isLoggedIn;
let button;
if(isLoggedIn){
button = <LogoutButton onClick={this.handleLogoutClick} />;
}else{
button = <LoginButton onClick={this.handleLoginClick} />
}
return(
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
)
}
}
const element = <LoginControl />;
ReactDOM.render(
element,
document.getElementById(\'root\')
);
</script>
以上是关于react 事件的主要内容,如果未能解决你的问题,请参考以下文章
Android 事件分发事件分发源码分析 ( Activity 中各层级的事件传递 | Activity -> PhoneWindow -> DecorView -> ViewGroup )(代码片段
[React Testing] Use Generated Data in Tests with tests-data-bot to Improve Test Maintainability(代码片段