【问题标题】:ReactJs get data From Props instead of State [closed]ReactJs 从道具而不是状态中获取数据 [关闭]
【发布时间】:2017-06-13 10:34:46
【问题描述】:

我如何从 props 获取我的数据,而不是从状态 im new 做出反应并且真的不知道如何处理它是我的垃圾箱:my app

有什么建议或例子吗?

【问题讨论】:

  • State 用于一个组件,而 props 用于将值从一个组件传递到另一个组件现在告诉我为什么您需要在 props 中的状态数据?或者让我知道您想在示例应用中做什么?
  • 我想稍后从 props 也从另一个组件接收数据,所以我必须用无状态组件重写它

标签: reactjs properties state


【解决方案1】:

我已更改您应用程序中的代码请在此处查看Demo

import React from 'react'
import {render} from 'react-dom'
import { CSSTransitionGroup } from 'react-transition-group'



class SendData extends React.Component{
  constructor(props) {
    super(props);
     this.state = {
      images: [
        'http://via.placeholder.com/350x150',
        'http://via.placeholder.com/350x151'
      ],
      currentImage: 0
    };
    this.fadeImage=this.fadeImage.bind(this);
  }
  fadeImage(e) {
    e.preventDefault();
    this.setState({currentImage: (this.state.currentImage + 1) % this.state.images.length})
  }
  render()
  {

    return(
      <FadeImage images={this.state.images} currentImage={this.state.currentImage} fadeImage={this.fadeImage}/>
     )
  }
}
class FadeImage extends React.Component {

  constructor(props) {
    super(props);
  }



  render() {
    return (
            <div className="image">
      <CSSTransitionGroup
        transitionName="example"
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300}
        >
          <section>
            <button className="button" onClick={this.props.fadeImage.bind(this)}>Click!</button>
            <img src={this.props.images[this.props.currentImage]}/></section>
        </CSSTransitionGroup>
        </div>
      );
    }
  }


render(<SendData />, document.querySelector('#app'))

【讨论】:

    猜你喜欢
    • 2021-01-31
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 2015-12-02
    • 2018-07-10
    • 1970-01-01
    相关资源
    最近更新 更多