一、简单的方法
1.效果图
2.代码
import React, { Component } from 'react';
import './App.css';
import on from './on.png';
import off from './off.png';
class App extends Component {
constructor(props) {
super(props);
this.state = {
touchState: false
}
}
touchStart() {
this.setState({ touchState: !this.state.touchState });
}
render() {
return (
<div className="App">
<div onClick={this.touchStart.bind(this)}>
<img src={this.state.touchState ? on : off} />
<p >{this.state.touchState ? 'open' : ''}</p>
</div>
</div>
);
}
}
export default App;
3.注意:其中on.png,off.png需要放到对应目录下,这两张图片需要提前下载,下图是我的文件目录
4.注意:很多时候,由于页面内可能不止一个按钮,为了使每个按钮互相不影响,应该将上面的单独写一个js文件,封装起来,在需要按钮的地方再引入进去,这样按钮之间点击不会受影响
二、通过从父组件设置值,传入子组件(推荐使用)实现父子组件之间的传值
1.子组件ToggleButton.js
此处的... props.data,要根据你父组件设置的值打印出来看结构才能确定。
import React, { Component } from "react";
import on from './on.png';
import off from './off.png';
class ToggleButton extends Component {
constructor(props) {
super(props);
this.state = {
... props.data
};
}
touchStart() {
this.setState({ bottom:!this.state.bottom });
}
render =()=> {
console.log('this.state.text',this.state.text)
return (
<div onClick={this.touchStart.bind(this)}>
<img src={this.state.bottom ? on : off} />
<p style={{display:this.state.bottom?'none':'block'}}>{this.state.text}</p>
</div>
);
}
}
export default ToggleButton
2.父组件App.js
只粘贴部分重要代码
import ToggleButton from './ToggleButton'
class DeviceList extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<ToggleButton data={{bottom: false, text: Patients.fullName}} />
</div>
);
}
}