切换按钮
(在React的模板基础上编写)
index.js
import React from 'react';
import ReactDOM from 'react-dom';
// import HiddenButton from './components/hiddent'
class Home extends React.Component {
constructor (props) {
super (props);
this.state = {
isLogin :true
}
this.handleClick = this.handleClick.bind(this);
this.changelClick = this.changelClick.bind(this);
};
//隐藏按钮
handleClick () {
this.setState ({
isLogin:false
})
};
// 显示按钮
changelClick () {
this.setState ({
isLogin:true
})
};
render () {
var isLogin = this.state.isLogin;
let button;
if (isLogin) {
// 把组件按钮 存储到变量中
button = <ShowButton onClick={this.handleClick}/>
} else {
button = <HiddenButton onClick={this.changelClick}/>
}
return (
<div>
{/* //DOM */}
<Blue isLogin={isLogin}/>
{/* 展示变量 */}
{button}
</div>
)
}
};
function HidderContent (props) {
return <div>隐藏内容</div>
};
function ShowContent (props) {
return <div>显示内容</div>
};
function Blue (props) {
var isLogi = props.isLogin;
if (isLogi) {
return <HidderContent />
} else {
return <ShowContent />
}
};
function ShowButton (props) {
return (
<button onClick={props.onClick}>隐藏</button>
)
};
function HiddenButton (props) {
return (
<button onClick={props.onClick}>显示</button>
)
};
ReactDOM.render (
<Home />,
document.getElementById('root')
)
效果:
点击按钮,效果:
组件化:
例如,把拿到外面
import React from 'react';
//需要引入,否则会报错
function HiddenButton (props) {
return (
<button onClick={props.onClick}>显示</button>
)
};
export default HiddenButton;
在inde.js中引入
import HiddenButton from './components/hiddent'
2020年4月16日