javascript - 如何通过按下按钮更改 css 代码
问题描述
目标:
当您按下按钮“确定”时,名为 test2 的 id 元素应为非显示,名为 test1 的 id 元素应为支持 css 代码的显示块。
并且还请考虑位于 css 代码中的文本的颜色。
问题:
我不知道如何解决。
为了实现目标,需要在源代码中进行哪些更改?
Stackblitz:
https ://stackblitz.com/edit/react-modal-gdh4hp ?
信息:
*我是 Reactjs 的新手
谢谢!
index.js
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Modal } from './modal';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
modal: true
};
}
handleCloseModal = () => {
alert('ddd');
};
render() {
const { modal } = this.state;
const non = {
display: 'none',
color: 'yellow'
};
const block = {
display: 'block',
color: 'yellow'
};
return (
<div>
{modal ? (
<Modal
onClose={() => {
this.setState({ modal: false });
}}
>
<div id="test1" style={non}>Awesome1</div>
<div id="test2">Awesome2</div>
<button onClick={() => this.handleCloseModal()}>ok</button>
</Modal>
) : (
<button
onClick={() => {
this.setState({ modal: true });
}}
>
Show modal
</button>
)}
</div>
);
}
}
render(<App />, document.getElementById('root'));
modal.js
import React from 'react';
export class Modal extends React.Component {
render() {
const { children, onClose } = this.props;
return (
<div style={{position: "absolute", top: 0, left: 0, width: "100%", height: "100%", background: "gray"}} onClick={ev => onClose()}>
<div
style={{margin: "auto", background: "white", border: "red", width: "500px", height: "300px"}}
onClick={ev => ev.stopPropagation()}>
{ children }
</div>
</div>
);
}
}
解决方案
您可以使用状态
class App extends Component {
constructor() {
super();
this.state = {
modal: true,
showBlock: "",
showNon: "",
color: ""
};
}
handleCloseModal = () => {
this.setState({showBlock: "block"});
this.setState({showNon: "none"});
this.setState({color: "yellow"});
alert('ddd');
};
render() {
const { modal } = this.state;
return (
<div>
{modal ? (
<Modal
onClose={() => {
this.setState({ modal: false });
}}
>
<div id="test1" style={{display: this.state.showBlock, color: this.state.color}}>Awesome1</div>
<div id="test2" style={{display: this.state.showNon, color: this.state.color}}>Awesome2</div>
<button onClick={() => this.handleCloseModal()}>ok</button>
</Modal>
) : (
<button
onClick={() => {
this.setState({ modal: true });
}}
>
Show modal
</button>
)}
</div>
);
}
}
render(<App />, document.getElementById('root'));
推荐阅读
- javascript - Sinon.spy() & jest.spyOn - TypeError: Attempted to wrap undefined property getTableData as function
- java - 如何将未知的类类型发送到方法并为该类生成参数
- laravel - 如何修复“方法 Illuminate\Database\Schema\Blueprint::class 不存在。”
- python - 使用while循环从函数返回变量
- mysql - The syntax of this MySQL logic?
- laravel-5 - 使用 swagger 在 laravel 中出现错误 419(未知状态)
- python - 使用 pymc3 对 MCMC 进行采样时,如何在可能性上添加 L1 正则化?
- web - 如何在 Weblogic 12.1.1 中导出数据源
- c - 如何使用 ## 运算符连接和评估宏
- php - PHP只更改ini文件中的一个值