2016-08-31 65 views
0

我正在寻找克隆使用与原始组件相同的“机制”的反应组件,该组件不依赖于它。这里是我的组元,一个小柜台(我是新来的反应,尽我所能去学习它)具有不同属性/状态的克隆反应组件

class BreakCount extends React.Component { 

    constructor(props) { 
    super(props); 
    this.state = {init: props.init} 
    this.drop = this.drop.bind(this) 
    this.add = this.add.bind(this) 
    } 

    drop() { 
    if(this.state.init > 1) { 
     this.setState ({ 
     init: this.state.init - 1 
    }); 
    } 
    } 

    add() { 
    this.setState({ 
     init: this.state.init + 1 
    }) 
    } 


    render() { 
    return (<div id = 'bc'> 
     <button onClick={this.drop}>-</button> 
     <button>{this.state.init}</button> 
     <button onClick = {this.add}>+</button> 
     </div>) 
    } 
} 

如果妳不明白,想的东西做同样的事情,但有不同的状态。我可以将新组件重写为原始组件,但我认为这不是正确的方式。

+0

我想你可以写**扩展新的组件**你的组件和超载要表现不同 –

+1

一些方法@Ivan Shmidt我可以从0改写它,但这不是我要找的方式。 –

+0

你不清楚你想做什么。 'React.cloneElement'它可以帮助你。 –

回答

0

将属性值设置为状态值在React中是不好的做法。更好的方式使用你的组件与不同的道具,所有你需要的是传递道具和管理你的组件没有状态(普通数据除外)。根据这一点,如果你想要克隆的元素,你可以使用:

React.cloneElement(element, {prop1: "a", prop2: "b", ...}) 

或只使用你的组件以不同的道具为:

<Element prop1="a" prop2="b" /> 
<Element prop1="c" prop2="d" /> 

在这种情况下,你需要建立一个在你的组件层次结构顶部存储(例如,redux,react-redux等),任何你打算在状态中改变的东西都会在store中改变它,这会导致你的根组件重新渲染并将新的道具传递给你的孩子组件)。

+1

我会看看我能做些什么。 –

0

如果你想重复使用不同道具的组件severalTimes。这里有一个例子:

import BreakCount from './breakCount.jsx'; 
export default class ParentClass extends React.Component{ 
    render() { 
     return(
      <div> 
       <BreakCount init={3}/> 
       <BreakCount init={1}/> 
       <BreakCount init={200}/> 
      </div> 
     ); 
    }  } 

添加导出到breakCount类:

export default class BreakCount extends React.Component { 

    constructor(props) { 
    super(props); 
    this.state = {init: props.init} 
    this.drop = this.drop.bind(this) 
    this.add = this.add.bind(this) 
    } 

    drop() { 
    if(this.state.init > 1) { 
     this.setState ({ 
     init: this.state.init - 1 
    }); 
    } 
    } 

    add() { 
    this.setState({ 
     init: this.state.init + 1 
    }) 
    } 


    render() { 
    return (<div id = 'bc'> 
     <button onClick={this.drop}>-</button> 
     <button>{this.state.init}</button> 
     <button onClick = {this.add}>+</button> 
     </div>) 
    } 
}