2016-07-28 104 views

回答

0

这取决于你想如何在应用中跟踪状态.. here是跟踪父组件的状态的例子。基本上你有一个单独的父App组件,它跟踪每个图像的状态,然后是一个Image组件,该组件可以使用或不使用边框来呈现,这取决于作为道具传递的App状态片段。请参阅代码以了解我的意思。另一种方法是让活动状态存在于每个图像组件本身内。

该代码有一些有趣的功能,主要是由于利用ES6的几个方面更加简洁,以及React's immutability helper帮助以不可变的方式更新状态数组,以及lodash的times方法来协助创建我们的初始状态数组。

码(部分缩进的得到了来自的jsfiddle拷贝有点糊涂..):

function getImage() { 
    return { active: false }; 
} 

class App extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { images: _.times(6, getImage) }; 
    this.clickImage = this.clickImage.bind(this); 
    } 
    clickImage(ix) { 
    const images = React.addons.update(this.state.images, { 
     [ix]: { $apply: x => ({ active: !x.active}) } 
    }) 
    this.setState({ images }); 
    } 
    render() { 
    const { images } = this.state; 
    return (
     <div> 
     { images.map((image, ix) => 
      <Image 
       key={ix} 
       ix={ix} 
       active={image.active} 
       clickImage={this.clickImage} />) } 
     </div> 
    ); 
    } 
}; 

class Image extends React.Component { 
    render() { 
    const { ix, clickImage, active } = this.props; 
    const style = active ? { border: '1px solid #021a40' } : {}; 
    return <img 
       style={style} 
       src={`https://robohash.org/${ix}`} 
       onClick={() => clickImage(ix)}/>; 
    } 
} 

ReactDOM.render(
    <App />, 
    document.getElementById('container') 
); 

然后是什么样子:

Example gif

+0

我是假设你想由于您包含“reactjs”标签而产生的反应答案。 – John

0

只需为点击添加一个“选定”类的事件处理程序,然后将该选定类设置为在CSS中具有边框。

.selectableImg { 
 
    border: solid 1px transparent; 
 
    margin: 10px; 
 
} 
 

 
.selectableImg.selected { 
 
    border: solid 1px blue; 
 
} 
 
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/> 
 
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/> 
 
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/> 
 
<img class="selectableImg" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/> 
 

 
<script> 
 
    var images = document.querySelectorAll(".selectableImg"); 
 
    
 
    images.forEach(function(i) {i.addEventListener("click", function(event) { 
 
    i.classList.toggle("selected"); 
 
    })}); 
 
    </script>

相关问题