0

I want the button to be dynamically created and used when the onPress event occurs. Ask for help from great and kind friends.

I want { in screen one Button , -> Button click -> create one Button -> so we have two button }

it is my code

import React, { Component } from 'react'
import { Button } from 'react-native'
const Test = () => { 
    return( 
        <Button title='test' onPress={<Button title='test1'/>}/> 
    ) 
} 
export default Test 

or

import React, { Component } from 'react'
import { Button } from 'react-native'
const Test = () => { 
    return( 
        <Button title='test' onPress={ButtonRender}/> 
    ) 
}
const ButtonRender =():any=>{
    return <Button title='test1'/>
}
export default Test 

I have a problem. It is not created Button. I need help

ggorlen
  • 44,755
  • 7
  • 76
  • 106
syu
  • 3
  • 1

1 Answers1

0

You can't render code inside onPress method.

onPress={ButtonRender} 
 

This piece of code will not render the code to the virtual dom. Basically You can't return value from onPress instead you can change the state of component this causes the component to rerender.

So How you can resolve this(another approach) just an example Not tested it

import React, { Component } from 'react'
import { Button,Text } from 'react-native'
  function TestUseState() {

  const [buttonArr, setButtonArr] = React.useState([]);
const renderButtons = () =>{
  return buttonArr.map ((item,index)=> 
                         <Button key={index} title= "your title"> </Button > 
                       )
} 
  return (
    <>
      <Text>Buttons List</Text>
      {renderButtons()}
     <Button onPress={() => setButtonArr( [...buttonArr , "Unique Index of new Button"] )} title="Add Button"></Button> 
    </>
  )
}
Syed Qasim Ahmed
  • 1,352
  • 13
  • 24
  • This workaround creates a button but causes an error. When the button is pressed, an error of'Each child in a list should have a unique "key" prop.' occurs. Even if you put a value that changes by +1 in "Unique Index of new Button" and enter a unique key, an error occurs. I need help. – syu Jan 11 '21 at 12:52
  • Answer Updated you should pass `key` props when you are mapping an array – Syed Qasim Ahmed Jan 11 '21 at 13:13
  • I am curious if you are talking about'interface props{~~}'. If it is correct, I am wondering if I need to input the key in'~~' and put it in'map' But I assigned a different value each time, but I got an error. Is there a difference from receiving user input? – syu Jan 11 '21 at 23:56