反应:在所选图像周围添加突出显示的边框 [英] REACT: Add highlighted border around selected image

查看:47
本文介绍了反应:在所选图像周围添加突出显示的边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选择图片时,我希望在图片周围有边框.因此,如果我有6张图片并选择3张,则希望在这些图片周围突出显示边框.问题是,我该怎么办?我正在使用React解决这个难题.

解决方案

这取决于您要如何跟踪应用程序中的状态..

I want a border around the picture when I select it. So if I have 6 pictures and choose 3, I would like to have highlighted borders around those images. Question is,How can I do this? EDIT: I am using React for this dilemma.

解决方案

This depends on how you want to track state in your app.. here is an example which tracks the state in the parent component. Essentially you have a single parent App component which tracks the state for each image, and then an Image component which renders either with or without a border, depending on a piece of the App state which gets passed down as a prop. Refer to the code to see what I mean. An alternative would be to have the active state live within each Image component itself.

The code has a number of interesting features mainly due to leveraging several aspects of ES6 to be more concise, as well as React's immutability helper to help update the state array in an immutable way, and lodash's times method to assist in creating our initial state array.

Code (some of the indenting got a bit muddled in the copy from 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')
);

And then what it looks like:

这篇关于反应:在所选图像周围添加突出显示的边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆