Return of onPress within Components

Asked

Viewed 209 times

0

Good night.

I’m having a little problem with the return of an Onpress from a Touchableopacity, inside an element. Basically, sometimes it returns the action, but most of the time it does not.

The code looks like this (briefly):

Neworder

const [photos, setPhotos] = useState([]);

{photos !== '' && photos !== null && photos !== undefined ? (<PicturePreview pictures={photos} onPressItem={onDeletePicture} />) : null}

const onDeletePicture = (index) => { //exclui o item do state photos, e setPhotos novamente, com o novo array para renderizar o <PicturePreview/>}

The state photos is powered with the date.Ri of the photo taken by the camera - so far, ok, everything works perfectly. When it arrow value, it renders the component <PicturePreview />, which I hope will return an onPress index to delete the array’s Uri, and render again.

Picturepreview:

import PreviewItem from './picturePreviewItem';

const PicturePreview = ({pictures, onPressItem}) => {
  const renderItems = () => {
    if (pictures.length > 0) {
      let elements = [];
      pictures.map((data, index) => {
        if (data !== undefined) {
          elements.push(
            <PreviewItem key={index} index={index} item={data} onPressItem={onPressDelete}/>
          );}
      });
      return elements;
    }
  };

  return (
    <View style={[styles.container, pictures.length > 0 ? styles.containerFilled : '',]}>
      {renderItems()}
    </View>
  );
};

Picturepreviewitem:

const PicturePreviewItem = ({item, index, onPressDelete}) => {
  const indexValue = index;
  return (
    <View style={styles.containerPreview}>
      <Image style={styles.imagePreview} resizeMode="contain" source={{uri: item}} />
      <TouchableOpacity onPress={(f) => onPressDelete(indexValue)}>
        <Icon name="cancel" style={styles.deletePictureIcon} />
      </TouchableOpacity>
    </View>
  );
};

Anyway, as I said, sometimes by clicking on the Touchableopacity, I can perform the function onDeletePicture of the Neworder page, but, most of the time, the press does not draft any reaction.

All Imports are duly declared (React, view, icon, etc...). The problem, by the tests I did with console.log, is in the Picturepreviewitem component, which does not respond to onPress (originating from there) when triggered.

Note: I am not having any black screen error.

Thank you.

  • got it ???...

1 answer

0


Their function pass names are all wrong, there’s no way to work anyway and in fact they’re not working at all, because if the name is wrong logically it shouldn’t work at all, pay attention, when passing value inside the component it must respect the name and that’s not what is happening, so:

Component PicturePreviewItem

import PicturePreviewItem from './picturePreviewItem';

const PicturePreview = ({pictures, onPressItem}) => {
  const renderItems = () => {
    if (pictures.length > 0) {
      let elements = [];
      pictures.map((data, index) => {        
        elements.push(
            <PicturePreviewItem 
                key={index} index={index} 
                item={data} 
                onPressDelete={onPressItem}
            />
        );
      });
      return elements;
    }
  };

  return (
    <View style={[
        styles.container, pictures.length > 0 ? styles.containerFilled : '',
    ]}>
      {renderItems()}
    </View>
  );
};

Component PicturePreviewItem

const PicturePreviewItem = ({item, index, onPressDelete}) => {  
  return (
    <View style={styles.containerPreview}>
      <Image 
        style={styles.imagePreview}
        resizeMode="contain" 
        source={{uri: item}} />
        <TouchableOpacity onPress={(f) => onPressDelete(index)}>
            <Icon name="cancel" style={styles.deletePictureIcon} />
        </TouchableOpacity>
    </View>
  );
};

that is, the names of props have to be correspondents and be careful enough with their names all different I myself to analyze I ended up getting lost and this also relates to your programming, the change was in the name of the functions try to observe, I just have no way to test basically, but, I will propose just below an example in for you to have an idea what changes is the event name of the button the rest is the same thing, minimum example:

function Item({item, index, onClickRemove}) {
  return <div>{item.name}<button onClick={() => onClickRemove(index)}>Remover</button></div>;
}
function Items({datas, onClickRemove}) {
  return (
    <div>{datas.length > 0 && datas.map((item, index) =>(<Item item={item} index={index} onClickRemove={onClickRemove}/>))}</div>
  )
}
function App() {
  const initialValues = [
    {'id': 1, 'name': 'name 1'},
    {'id': 2, 'name': 'name 2'},
    {'id': 3, 'name': 'name 3'},
    {'id': 4, 'name': 'name 4'},
    {'id': 5, 'name': 'name 5'}   
  ];
  const [datas, setDatas] = React.useState(initialValues);
  function onClickRemove(index) {
    let items = [...datas];
    items.splice(index, 1);
    setDatas(items);
  }
  function loadInitialValues(){
    setDatas(initialValues);
  }
  return (<div><Items datas={datas} onClickRemove={onClickRemove}/>{datas.length === 0 && <button onClick={loadInitialValues}>Carregar</button>}</div>);
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

and note well the names are passed to all componentes with the same name to maintain a standard.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.