React获取一个Button的ID

时间:2017-09-26 19:25:55

标签: reactjs

我试图将按钮的ID传递给某个功能,但是我无法将任何事情发生。我将根据用户是否点击" increaseButton"来改变字体大小的功能。或"减少按钮"这很容易,但我无法获得按钮的ID。 的元器件

fontSize(e) {
      console.log(e.target.id);
 }

渲染

 <button id="decreaseButton"  hidden={isHidden} onClick {this.fontSize.bind(this)}>-</button>

1 个答案:

答案 0 :(得分:1)

正如您所提到的,您将根据increasedecrease操作更改字体大小。为什么不使用这两个按钮并将它们与特定操作绑定在一起,这样您就不必依赖任何类型的属性?

const Button = ({ children, onClick }) => <button onClick={onClick}>{children}</button>

class App extends React.Component {
  constructor() {
    super()

    this.state = {
      fontSize: 16,
    }

    this.handleDecrease = this.handleDecrease.bind(this)
    this.handleIncrease = this.handleIncrease.bind(this)
  }

  handleDecrease() {
    // Sample rule: fontSize should no be less than 10
    this.setState({ fontSize: Math.max(this.state.fontSize - 1, 10) })
  }
  
  handleIncrease() {
    // Sample rule: fontSize should not be greater than 30
    this.setState({ fontSize: Math.min(this.state.fontSize + 1, 30) })
  }

  render() {
    return (
      <div>
        <Button onClick={this.handleDecrease}>
          Decrease font
        </Button>
        <Button onClick={this.handleIncrease}>
          Increase font
        </Button>
        
        <div>Current fontSize: {this.state.fontSize}</div>
        <div style={{ fontSize: this.state.fontSize }}>Preview</div>
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>