Reactjs 如何使用React添加宽度div?

Reactjs 如何使用React添加宽度div?,reactjs,Reactjs,添加一个div和一个按钮。单击时,将div的宽度增加3 px。添加一个重置按钮,允许您将状态重置为初始宽度 const three = (e) => { let value = e.target.value; this.setState({ three: value }); } 我们需要定义一个要切换的状态变量,并且基于它的状态,我们还可以切换宽度,因此我们的代码如下-: 工作演示-> 在js文件中: render() { return ( <div>

添加一个div和一个按钮。单击时,将div的宽度增加3 px。添加一个重置按钮,允许您将状态重置为初始宽度

const three = (e) => {
 let value = e.target.value;
 this.setState({ three: value });
}

我们需要定义一个要切换的状态变量,并且基于它的状态,我们还可以切换宽度,因此我们的代码如下-:

工作演示->

js
文件中:

render() {
    return (
      <div>
        <div className={`flexible-width ${this.state.increaseWidth ? "long-width" : "short-width"}`} onClick={() => this.setState({increaseWidth: !this.state.increaseWidth})}></div>
      </div>
    );
  }
.flexible-width{
  background: red;
  height: 50px;
}
.long-width{
  width: 150px;
}
.short-width{
  width: 50px;
}

我们需要定义一个要切换的状态变量,并且基于它的状态,我们还可以切换宽度,因此我们的代码如下-:

工作演示->

js
文件中:

render() {
    return (
      <div>
        <div className={`flexible-width ${this.state.increaseWidth ? "long-width" : "short-width"}`} onClick={() => this.setState({increaseWidth: !this.state.increaseWidth})}></div>
      </div>
    );
  }
.flexible-width{
  background: red;
  height: 50px;
}
.long-width{
  width: 150px;
}
.short-width{
  width: 50px;
}

对于简单的宽度样式,请这样做。如果您想进行广泛的样式设计,请转向使用
CSS
类并在运行时更改类

import React from 'react';

class Component extends React.Component {

  state = {
    clicked: false
  }

  render() {
    return ( <div>
      <div style = {{ width: this.state.clicked ? "100px" : "103px" }>
        //div content here
      </div> 
      <button onClick = {() => this.setState({clicked: !this.state.clcked})}> 
        { clicked ? "Reset" : "Increase Width"} 
      </button>
    </div>)
  }
}

export default Component;
从“React”导入React;
类组件扩展了React.Component{
状态={
单击:false
}
render(){
报税表(
//div内容在这里
this.setState({单击:!this.state.clcked})}>
{单击?“重置”:“增加宽度”}
)
}
}
导出默认组件;

对于简单的宽度样式,请这样做。如果您想进行广泛的样式设计,请转向使用
CSS
类并在运行时更改类

import React from 'react';

class Component extends React.Component {

  state = {
    clicked: false
  }

  render() {
    return ( <div>
      <div style = {{ width: this.state.clicked ? "100px" : "103px" }>
        //div content here
      </div> 
      <button onClick = {() => this.setState({clicked: !this.state.clcked})}> 
        { clicked ? "Reset" : "Increase Width"} 
      </button>
    </div>)
  }
}

export default Component;
从“React”导入React;
类组件扩展了React.Component{
状态={
单击:false
}
render(){
报税表(
//div内容在这里
this.setState({单击:!this.state.clcked})}>
{单击?“重置”:“增加宽度”}
)
}
}
导出默认组件;