【问题标题】:how to pass new prop to rendered component如何将新道具传递给渲染组件
【发布时间】:2016-06-01 16:47:34
【问题描述】:

假设你有一个名为 Banner 的渲染组件;

var Banner = React.createClass({
  getInitialState: function() {
     return { text: this.props.word };
  },
  render: function(){
     return <div>this.state.text</div>
  }
}) 

var banner = ReactDom.render( <Banner word="hello" />, document.getElementById('banner'));

是否可以在不更换组件的情况下更新 Banner 的 props?例如下面的函数

function changeText(component, text){
    // change text inside banner
}
changeText(banner, 'Goodbye') 

显然在这个例子中,用新文本重新初始化横幅会容易得多,但我希望横幅在文本更改时有动画,但在初始化时没有动画

【问题讨论】:

标签: reactjs react-jsx jsx


【解决方案1】:

你的例子有点简单。您的实际问题可能是多方面的,但我会尝试最有可能的情况。

如果目标是修改 div 的内容,那么答案就是根本不使用 props。这正是你的状态!

var Banner = React.createClass({
    render: function() {
        return <div>this.state.word</div>
    },
    getInitialState: function(){
        return {word: this.props.word};
    }

    changeWord: function(word){
        this.setState({word: word});
    }
});

编辑:

如果您尝试从嵌入页面其他地方的 vanilla js 修改组件:

我认为在这种情况下你最好的选择是利用一些(如果不是全部)Flux 设计模式:https://facebook.github.io/flux/docs/overview.html#content

如果不是整个 Flux 范例,您至少可以利用 Flux 处理“商店”的方式,它本质上只是 Node.js EventEmmiters:https://nodejs.org/api/events.html

var BannerStore = new EventEmmitter();

var Banner = React.createClass({
    render: function() {
        return <div>this.state.word</div>
    },
    getInitialState: function(){
        return {word: this.props.word};
    },
    changeWord: function(){
        this.setState({word: BannerStore.word});
    },

    componentDidMount: function(){
        BannerStore.on('banner_change', this.changeWord);
    },

    componentWillUnmount: function(){
        BannerStore.removeListener('banner_change', this.changeWord);
    }
});

function changeText(component, text){
    if(component === 'banner'){
        BannerStore.word = text;
        BannerStore.emit('banner_change');
    }
}
changeText(banner, 'Goodbye') 

从长远来看,使用全通量范式会更干净,但不能合理地输入 SO。

【讨论】:

  • 但这只有在Banner“拥有”该数据时才有效,它很可能不会这样做。您必须找到某种不使用 props 将数据注入组件的方法;我能想到的任何方式似乎都非常“un-React-y”。
  • 那么数据是从哪里来的呢?这似乎是您问题的症结所在,但您没有向我们提供线索!
  • 我不是 OP :-) 在 OP 的示例中,他似乎是从道具传递消息。
  • 哈哈,哎呀。 :O。这就是为什么我开始回答时要求提供更多信息。在不知道数据来源的情况下,任何答案都可能相互矛盾,因为没有一个组件可以满足所有可能的需求。
  • 那个函数在哪里?父组件?子组件?完全分离反应树?
猜你喜欢
  • 1970-01-01
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
  • 1970-01-01
  • 2020-12-26
  • 1970-01-01
相关资源
最近更新 更多