在不使用 react-native-web 的情况下为 ReactJS 创建“TouchableOpacity”

gar*_*mac 6 javascript reactjs react-component

我想创建一个包装器组件,它的行为类似于react- natives<TouchableOpacity/>而不使用react-native-web.

我正在考虑管理状态并使用内联样式从.5到转换1为不透明度的东西,setInterval或者它应该是 css 转换。

有什么东西已经在那里了吗?

最好的方法是什么?

Cha*_*nda 8

You can achieve this affect with css transitions and using state to track when the user is clicking the button:

class App extends React.Component {

  state = {
    touched: false
  }
  
  toggleTouched = () => {
    this.setState( prevState => ({
      touched: !prevState.touched
    }));
  }
  
  handleMouseUp = () => {
    // Handle smooth animation when clicking without holding
    setTimeout( () => {
      this.setState({ touched: false });
    }, 150);
  }
  
  render () {
    const { touched } = this.state;
    const className = touched ? 'btn touched' : 'btn';
    return (
        <button 
          className={className}
          onMouseDown={this.toggleTouched}
          onMouseUp={this.handleMouseUp}
        >
          Touch Here
        </button>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
.btn {
  background: #ededed;
  padding: 10px 15px;
  border: none;
  outline: none;
  cursor: pointer;
  font-size: 15px;
  
  opacity: 1;
  transition: opacity 300ms ease;
}

.touched {
  opacity: 0.5;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)