如何通过更改状态来更改URL

时间:2020-03-21 20:40:34

标签: reactjs

我有一个父母和两个孩子。我正在尝试通过按按钮来更改图像URL,但是没有成功……我似乎无法将数据从按钮子级传递到图像子级。

父母:

class Main extends React.Component {
  constructor() {
    super();
    this.state = {
      isHidden: true,
      imageUrl: ""
    };
  }
  showImage = () => () => {
    this.setState({
      imageUrl:
        "https://cdn.pixabay.com/photo/2020/03/19/04/58/coconut-trees-4946270_960_720.jpg"
    });
  };

  render() {
    return (
      <div>
        <ImageButton onClick={this.showImage()} />
        <Image />
      </div>
    );
  }
}

ButtonChild:

export default class ImageButton extends Component {
  render() {
    return (
      <div>
        <button onClick={this.props.showImage}>New image</button>
      </div>
    );
  }
}

ImageChild:

export default class ProfilePicture extends Component {
  render() {
    return <img src="{props.imageUrl}" />;
  }
}

1 个答案:

答案 0 :(得分:1)

它有效,请注意一些更改。希望对您有帮助。

父母:

class Main extends React.Component {
  constructor() {
    super();
    this.state = {
      isHidden: true,
      imageUrl: ""
    };
  }

  showImage = () => () => {
    this.setState({
      imageUrl:
        "https://cdn.pixabay.com/photo/2020/03/19/04/58/coconut-trees-4946270_960_720.jpg"
    });
  };

  render() {
    return (
      <div>
        <ImageButton clicked={this.showImage()} />
        <ProfilePicture imageUrl={this.state.imageUrl} />
      </div>
    );
  }
}

ButtonChild:

export default class ImageButton extends Component {
  render() {
    return (
      <div>
        <button onClick={this.props.clicked}>New image</button>
      </div>
    );
  }
}

ImageChild:

export default class ProfilePicture extends Component {
  render() {
    return <img src={this.props.imageUrl} />;
  }
}