【发布时间】:2018-10-28 13:38:57
【问题描述】:
我在我的 react 应用上创建了一个 LogOut 按钮组件。
看起来是这样的:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export class LogOutButton extends Component {
static contextTypes = {
store: PropTypes.object.isRequired,
};
handleClick = () => {
this.context.store.dispatch();
};
render() {
return <button type="button" onClick={this.handleClick}>Logout</button>;
}
}
我想要做的就是在 index.js 中使用这个组件,这样当用户单击 LogOut 按钮时,他将被定向到 www.google.com。
我应该如何更改 LogOutButton 组件,以便它将用户重定向到 google.com?
index.js里面的组件应该如何使用?
这是我的 index.js:
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { LogOutButton } from './components/LogOutButton.js';
class Home extends React.Component {
displayName = Home.name;
state = {
result: 0,
val1: 0,
val2: 0,
};
handleChangeOne = event => {
this.setState({ val1: event.target.value });
};
handleChangeTwo = event => {
this.setState({ val2: event.target.value });
};
add = () => {
this.setState({
result: parseInt(this.state.val1) + parseInt(this.state.val2)
});
};
render() {
return (
<div>
<h1>Hello world! The result is: {this.state.result}</h1>
<input type="text" onChange={this.handleChangeOne} />
+
<input type="text" onChange={this.handleChangeTwo} />
= <br />
<button onClick={this.add}>Add</button>
<br/><br/>
<button onClick={LogOutButton}>Log Out</button>
</div>
);
}
}
我知道在render()里面写这行是错误的
<button onClick={LogOutButton}>Log Out</button>
但是我不知道如何使 LogOutButton 组件工作。
提前致谢。
【问题讨论】:
标签: javascript reactjs rendering react-component