更改组件的道具。不会更新所有相关项目

时间:2016-04-07 03:20:23

标签: react-native

render(){
var borderStyle=this.props.isSelected?
{ borderBottomWidth:2, borderColor:'#333'}:
{ borderBottomWidth:0, borderColor:'#333'};

var displayImage=this.props.isSelected?
this.props.selectedImg:
this.props.unSelectedImg;

return (
  <TouchableHighlight
    underlayColor='#999'
    onPress={()=>this.onPressHandler()}
    style={styles.container}>
    <View style={[styles.content,borderStyle]}>
      <Image style={styles.image}
             source={displayImage}/>
    </View>
  </TouchableHighlight>
);
}

上面的代码用于在选择按钮时更新边框样式和显示图像

但只有边框样式发生了变化,图像也没有变化。

但如果我删除以下代码,图像将会更改。似乎它只更新了一个组件而不是所有相关项目。

  var borderStyle=this.props.isSelected?
    { borderBottomWidth:2, borderColor:'#333'}:
    { borderBottomWidth:0, borderColor:'#333'};

有人知道这个问题吗?

父组件代码如下:

var TabBar=React.createClass({
  buttons:
  [
    0,1,2,3
  ],
  selectedImage:
  [
    require('./../../../images/toolBar/selected/categories.png'),
    require('./../../../images/toolBar/selected/Article.png'),
    require('./../../../images/toolBar/selected/Stores.png'),
    require('./../../../images/toolBar/selected/Me.png')
  ],
  unSelectedImage:
  [
    require('./../../../images/toolBar/unSelected/categories.png'),
    require('./../../../images/toolBar/unSelected/Article.png'),
    require('./../../../images/toolBar/unSelected/Stores.png'),
    require('./../../../images/toolBar/unSelected/Me.png')
  ],
  getDefaultProps: function() {
    return {
      style:null
    };
  },
  getInitialState: function() {
    return {
      selectedIndex:0
    };
  },
  onSelectedHandler(index){
    this.setState({
        selectedIndex:index
    });
  },
  gerenateButtons(){
    var items=[];
    var parent=this;
    this.buttons.map(function(index){
      var item=(
        <TabBarBtn
          key={index}
          index={index}
          selectedImg={parent.selectedImage[index]}
          unSelectedImg={parent.unSelectedImage[index]}
          isSelected={parent.state.selectedIndex==index}
          onSelected={id=>{parent.onSelectedHandler(id)}}/>
      );
      items.push(item);
    });
    return items;
  },
  render(){
    return (
      <View style={[styles.container,this.props.style]}>
        {this.gerenateButtons()}
      </View>
    );
  }
});

提前致谢

0 个答案:

没有答案