react控制文本内容的显示隐藏?

第一次写react+redux项目时遇到了问题,怎么在点击按钮时控制元素的显示隐藏?
图片描述

如图:
红框框整体是个框架,会有很多个这样的框架,当点击具体的某一个按钮,即数字1标示的按钮时,我需要将
1:.tipic-content的stylemax-height改为auto
2:.flod即数字2标示的style改为display: none
其实效果就是点击按钮,让显示更多的文字显示出来,.fold是一个底部的渐变到白色的效果而已。
然后再次点击时做相反的动作就行了。
这个其实用jquery做很方便,点击找到父类对应的class,修改样式就行了,但是现在用react做,不想用jquery,就不知道怎么做,用原生的js控制元素太啰嗦了,大家有什么好方法呢。

阅读 22.3k
4 个回答

不建议使用style进行样式的控制,可以定义.topic-intro-extended来修改max-height为auto, .fold也是同理

var Component = React.createClass({
  getInitialState:function(){
    return {
      topicExtended:false
    }
  },
  toggleClickHandler:function(){
    this.setState({
      topicExtended:!this.state.topicExtended
    });
  },
  render:function(){
    var topicCls = "topic-intro";
    var foldCls = "";
    if(this.state.topicExtended){
      topicCls+=" topic-intro-extended";
      foldCls+="fold";
    }
    return (
      <div>
        <div className="topic-content">
          <div className={topicCls}>blablabla</div>
          <div className={foldCls}>blablabla</div>
        </div>
        <div className="toggle-btn" onClick={this.toggleClickHandler}>click me</div>
      </div>
    )
  }
});

另外,对className的控制,建议使用classnames

因该是类似文章简介和点击阅读全文后展开全文的效果吧。这个要在state上设置一个属性,在需要改变的地方引入getState,然后通过绑定按钮(数字1标示按钮)改变state这个属性。如果用的是redux的话也差不多

仿照下面这个 给你要改变的组件加个style ,里面可以有类似display:{block}这样的属性
然后在需要点击的组件那里加个onClick事件,进行触发修改相应组件的style。

var divStyle = {
  color: 'white',
  backgroundImage: 'url(' + imgUrl + ')',
  WebkitTransition: 'all', // note the capital 'W' here
  msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};

ReactDOM.render(<div style={divStyle}>Hello World!</div>, mountNode);

https://facebook.github.io/re...

最终解决的思路就是通过redux去控制state的状态,从而达到隐藏显示的效果,例如本题的示例:

action的设计思路是:
export const toggle = (state = [], action) => {
    switch (action.type) {
        case 'expand':
            let newState = [].concat(state);
            newState[action.id] = !newState[action.id];
            return newState
        default :
            return state
    }
}
通过数组的真假控制topic-content,fold,toggle-btn状态的改变;

添加对toggle-btn的事件监听:
    toggleFont(id) {
        let dispatch = this.props.dispatch;

        dispatch({
            type: "expand",
            id: id
        })
    }
    //传递点击时的id值

这样,每次点击时就改变了state的状态,从而实现了显示隐藏效果。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题