简体   繁体   English

如何在React Native的按钮的onclick内传递参数?

[英]How to pass arguments within onclick of button in react native?

I am trying to pass a data (server response) as an argument of a button.Actually in my case there are certain type of workers (listing within cards ). 我试图将数据(服务器响应)作为按钮的参数传递,实际上我的情况是某些类型的工作程序(在卡片中列出)。 If clicked on a worker it should be saved to db with the corresponding worker's id.Upon clicking on the card of workers there will be a popup showing for confirmation.So if clicked on yes button I'm taking the corresponding worker's id and perform another fetch request for saving it to my db.But this is not working I'm confused how to pass arguments within onclick property of a button and take that argument within fetch method.Following is my code.I'm pasting only a portion of my code below. 如果单击了一个工作程序,则应将其与相应工作程序的ID一起保存到数据库中。单击工作程序卡时,将显示一个弹出窗口以供确认。因此,如果单击yes按钮,我将获取相应的工作人员的ID并执行另一个提取将其保存到数据库中的请求,但这无法正常工作,我很困惑如何在按钮的onclick属性中传递参数并在fetch方法中接受该参数,以下是我的代码,我只粘贴了一部分下面的代码。

updated code 更新的代码

export default  class FirstScreen extends Component {
  constructor(){
    super();
    this.state = {
      workers: [],
        }
  }
      componentWillMount(){
            fetch('http://192.168.1.3:3000/api/worker', {
              method:'GET',
              headers:{
                Accept: 'application/json'
              }
            })
            .then(response => response.json())
            .then(responseData =>
              this.setState({
              workers:responseData
              })
            )
      }
      onPressYes = (worker_id) => {

        fetch('http://192.168.1.3:3000/api/work_detail',{
          method:'POST',
          headers:{
            Accept:'application/json'
          },
          body:JSON.stringify({
            worker_id
          })
        })
      }
  render() {
    return (

      <View style={{flex:1}}>
      <Header />
      <ScrollView>
    {this.state.workers.map((a, index)=>
<Container>
 <CardSection>
      <TouchableOpacity
       onPress={() => this.popupDialog.show()}
      >
      <View style={{ maringTop: 10, marginLeft:120}}>
      <Image
              style={{ height: 100, width: 100 }}
            source={{ uri: a.work_type == 'Carpenter' ? images[0].image : images[1].image}}
             />
         <Text style={{marginLeft:20, fontSize:20}}>{a.work_type}</Text>
         </View>
         </TouchableOpacity>
 </CardSection>
</Container>
      <View style={styles.buttonContainer}>
       <TouchableOpacity onPress={() =>console.log('Clicked')}>
       <Button
       backgroundColor="#FF4500"
       title='View Status' />
       </TouchableOpacity>
      </View>
      </ScrollView>
      <PopupDialog
                ref={popupDialog => {
                  this.popupDialog = popupDialog;
                }}
                dialogStyle={{ backgroundColor: "#FFFFFF", height: 180, width:300, borderWidth:1,padding:10}}
                overlayBackgroundColor="#fff"
                dismissOnTouchOutside={true}
                     >
             <View style={styles.dialogContentView}>
             <Text style={{fontSize:18, margingTop:10,color:"#000000"}}>Are you sure you want to submit?</Text>
             <View style={{flexDirection:'row'}}>
             <View style={styles.button_1}>
             <Button
title="Yes"
color="#FF6633"
onPress={() => this.onPressYes(worker_id)}
/>
</View>
<View style={styles.button_1}>
<Button
title="No"
color="#FF6633"
onPress={() =>this._onPressNo() }
/>
</View>
            </View>
            </View>
              </PopupDialog>
   </View>
})
    );
  }
}

workers is the array I'm fetching from server. workers是我从服务器获取的数组。

Can you try replacing _onPressYes = (a.worker_id) with with _onPressYes = (worker_id) and then 您可以尝试将_onPressYes = (a.worker_id) with_onPressYes = (worker_id) ,然后

body:JSON.stringify({
   worker_id
})

Let me know if that helps. 让我知道是否有帮助。

What I usually do is return a function with the given parameter. 我通常要做的是返回具有给定参数的函数。 I mean wrap a function in a function like the following: 我的意思是将函数包装在如下函数中:

onClickHandler = (value) => () => {
   // do whathever you want.
};

<Component onClick={this.onClickHandler(yourValue)}/>

Because the problem in your code is that the function will be execute without calling the onClick event because when you pass the argument to a simple function you are already calling it. 因为代码中的问题在于该函数将在不调用onClick事件的情况下执行,因为将参数传递给简单函数时,您已经在调用它。

I hope it can help you :) 希望它能对您有所帮助:)

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

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