简体   繁体   English

有没有办法重用 react-native 中的组件?

[英]Is there a way to re use component in react-native?

I'm new in react-native and I can't figure out if this is possible what i mean is create a complement for example a button, it would be:我是 react-native 的新手,我不知道这是否可能我的意思是创建一个补充,例如一个按钮,它将是:

    Class button extends Component {
     
     render() {
         return (
            <Button title = "button"> </Button>
          );
       } 
    }

To use this I should import it and then add it to the render function where I want to use it:要使用它,我应该导入它,然后将它添加到我想使用它的渲染 function 中:

Import Button from "../component/Button.js"

    Class Hi extends component {
       
      render() {
         return (
            <Button></Button>
        );
       } 
    }

Now, my question is, imagine in the class hi there's another button, that button when i click on it it will automatically add the button from the class button, if a click it two times it has to add two new buttons, is like doing this:现在,我的问题是,想象在 class 嗨还有另一个按钮,当我点击它时,它会自动从 class 按钮添加按钮,如果点击两次它必须添加两个新按钮,就像在做这个:

Import Button from "../component/Button.js"

    Class Hi extends component {

      render() {
         return (
            <Button></Button>
            <Button></Button>
            <Button></Button>
        );
       } 
    }

What you can do is use a counter to count clicks.您可以做的是使用计数器来计算点击次数。

Import Button from "../component/Button.js"

Class Hi extends component {
  constructor(props){
    super(props)
    this.state = {
      buttonCount : 1
    }
    incrementCount = this.incrementCount.bind(this)
  }
  incrementCount(){
    let cnt=this.state.buttonCount
    this.setState({
      buttonCount : cnt+1
    })
  }
  render() {
    let buttons=[]
    for(let i=1;i<=this.state.buttonCount;i++){
      buttons.push(<Button key={i} onClick={incrementCount}/>)
    }
     return (
        {buttons}
    );
   } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM