在React组件中起作用

时间:2018-07-12 05:41:02

标签: html reactjs

我正在尝试学习React,所以如果这个问题掩盖了一些无知,请原谅我...但是我会尽量保持简单。

我的应用程序中有一个名为“ Starset0”的组件

就这样:

 import React from "react";

 const Starset0 = props => (
  <div id = "rating0">
   <img class = "star" id = "1" src = {require('./empty-star.png')} />
   <img class = "star" id = "2" src = {require('./empty-star.png')} />
   <img class = "star" id = "3" src = {require('./empty-star.png')} />
   <img class = "star" id = "4" src = {require('./empty-star.png')}/>
   <img class = "star" id = "5" src = {require('./empty-star.png')}/>
  </div>


 );

 export default Starset0;

尽管我要做的事情比较复杂,

让我们从简单开始:我将如何编写一个函数,该函数将导致单击任何图像(星号)的src更改为

{require('./full-star.png')}

2 个答案:

答案 0 :(得分:0)

使每颗星星都是其自身的组成部分。像这样:

class Star extends React.Component {
  render() {
    return (
      <img
        src={this.state.full ? fullStar : emptyStar}
        onClick={this.toggleFull}
      />
    );
  }

  constructor() {
    super();
    this.state = { full: false };

    this.toggleFull = this.toggleFull.bind(this);
  }

  toggleFull() {
    this.setState({ full: !this.state.full });
  }
}

您可能想通过一个道具说出多少颗满/空星,然后将其动态渲染,以传递给Starset。但这是另一个问题:-)

答案 1 :(得分:0)

  1. 您应该在文件顶部而不是在方法/组件内部导入/要求您的方法。原因是,组件代码将通过webpack或您使用的任何其他捆绑程序转换为本机JavaScript代码。

  2. 首先加载两个图像,然后使用onClick侦听器更改src。

所以您的问题的答案是

import React from "react";
// require the image src below
const fullStarSrc =
  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ0VTgrxQ2qHQsg64mHBLUHg7Lvd5JwD_sgRPfTxewBOrWhnvjqPQ";
const halfStarSrc =
  "https://visualpharm.com/assets/247/Star%20Half-595b40b85ba036ed117dab5e.svg";

class ExampleComponent extends React.Component {
  constructor(props) {
    super(props);
    this.changeSrc = this.changeSrc.bind(this);
  }

  changeSrc(e) {
    // This is example code and the condition to check might not be right
    // but this.elem.offsetTop will give you the element's current top position
    if (e.target && e.target.src) {
      e.target.src = fullStarSrc;
    }
  }

  render() {
    return (
      <div id="rating0">
        <img
          width="100px"
          height="100px"
          src={halfStarSrc}
          onClick={e => this.changeSrc(e)}
        />
        <img
          width="100px"
          height="100px"
          src={halfStarSrc}
          onClick={e => this.changeSrc(e)}
        />
        <img
          width="100px"
          height="100px"
          src={halfStarSrc}
          onClick={e => this.changeSrc(e)}
        />
        <img
          width="100px"
          height="100px"
          src={halfStarSrc}
          onClick={e => this.changeSrc(e)}
        />
        <img
          width="100px"
          height="100px"
          src={halfStarSrc}
          onClick={e => this.changeSrc(e)}
        />
      </div>
    );
  }
}

export default ExampleComponent;

您将在此处找到工作示例-Half Star to Full Star