无状态组件切换布尔值

时间:2017-05-09 12:47:25

标签: reactjs stateless

将以下代码转换为无状态组件的正确方法是什么?

export default class About extends Component {

  state = {
    showKitten: false
  }

  handleToggleKitten = () => this.setState({ showKitten: !this.state.showKitten });

  render() {
    const { showKitten } = this.state;
    const kitten = require('./kitten.jpg');
    return (
      <div className="container">
        {showKitten && <div><img src={kitten} alt="kitchen" /></div>}
      </div>
    );
  }
}

管理以定义道具等。以下代码用于记录消息。但是切换布尔值的最佳方法是什么?

const handleToggleKitten = () => {
  console.log('Hello from here');
  **// How to toggle the value of boolean here?**
};

const About = (props) => {
  const { showKitten } = props;
  const kitten = require('./kitten.jpg');
  return (
    <div className="container">
      {showKitten && <div><img src={kitten} alt="kitchen" /></div>}
    </div>
  );
};

About.defaultProps = {
  showKitten: false
};

About.propTypes = {
  showKitten: PropTypes.bool.isRequired
};

2 个答案:

答案 0 :(得分:3)

你应该有一个stateful组件呈现stateless组件并传递和更新道具

&#13;
&#13;
class App extends React.Component {
     
     state= {showKitten: false}
     handleToggleKitten = () => {
        this.setState((prevState, props) => ({
            showKitten: !prevState.showKitten
        }))
      };

     render()  {
         return (
              <About showKitten={this.state.showKitten} handleToggleKitten={this.handleToggleKitten}/>
         ) 

     }
}
const About = (props) => {
  const { showKitten } = props;
 
  return (
    <div className="container">
      {showKitten && <div><img src={"http://addolo.com/wp-content/uploads/2016/12/kitten-pics-uncategorized-84-astonishing-photo-ideas-kittens-cattime-black-and-white-pictures-funny-with-captionskitten-cutekitten.jpg"} alt="kitchen" /></div>}
      <button onClick={props.handleToggleKitten}>Toggle</button>
    </div>
  );
};


About.propTypes = {
  showKitten: React.PropTypes.bool.isRequired
};

ReactDOM.render(<App/>, document.getElementById('app'))
&#13;
<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="app"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

嘿颜晟有点晚了但试试这个。

let showKitten = false;


const handleToggleKitten = () => {
    console.log('Hello from here');
    **// How to toggle the value of boolean here?**
    showKitten = !showKitten;
};