React点击按钮显示对应颜色名称功能开发求助
代码修正方案
你现有代码存在多处逻辑遗漏和写法问题,以下是可直接运行的实现代码:
import React, { Component } from 'react'; class App extends Component { state = { // 存储要展示的颜色文字 showText: '', // 存储文字对应的颜色值 textColor: '' } // 按钮点击处理方法 onColorBtnClick = (text, color) => { this.setState({ showText: text, textColor: color }) } componentDidMount() { // 页面加载完成后默认触发红色按钮点击,匹配原代码的触发逻辑 this.onColorBtnClick('Red', 'red') } render() { return ( <div style={{ padding: '15px' }}> {/* 两个颜色按钮 */} <button id="btnGreen" onClick={() => this.onColorBtnClick('Green', 'green')} style={{ marginRight: '12px' }} > Green </button> <button id="btnRed" onClick={() => this.onColorBtnClick('Red', 'red')} > Red </button> {/* 下方颜色名称展示区域 */} <div style={{ marginTop: '20px', fontSize: '20px', color: this.state.textColor }}> {this.state.showText} </div> </div> ) } } export default App;
主要调整点
- 移除了冗余的全局document点击事件绑定,改为直接给按钮绑定专属点击事件,避免和页面其他按钮逻辑冲突,更符合React开发规范
- 实现了底部的颜色文本展示区域,文本颜色和选中的按钮标注颜色一致,匹配需求效果
- 将两个按钮纳入App组件的渲染逻辑中,统一由React管控
- 删除了未实现逻辑、也没有被调用的冗余
ColorChange组件 - 修正了原代码中选中不存在的id来触发点击的问题,页面加载后默认展示红色文本,匹配原代码的触发意图
内容的提问来源于stack exchange,提问作者user17403292
相关产品推荐
相关产品推荐

