【问题标题】:How to send state from child hook to parent state如何将状态从子钩子发送到父状态
【发布时间】:2019-10-03 17:44:20
【问题描述】:

我有一个下拉列表,我试图从中获取状态并将其传递给其父容器。我有很多问题试图解决这个问题。这是我下面的代码:

this.state = {
  title: null,
  postBody: null,
  giphyUrl: null,
  userIdto: null,

  displayGifPicker: false
}

上面是状态,我想输入下拉框给UserIdto的值

    getUserTo = (selectedUser) => {
  console.log(selectedUser)
  this.setState({ userIdto : selectedUser});
}

方法作为prop传递给组件

<NameDropDown onChange={this.getUserTo}/> 

在父组件中我有以下内容:

class PostBox extends Component {



constructor(props){
    super(props)
    this.state = {
      title: null,
      postBody: null,
      giphyUrl: null,
      userIdto: null,

      displayGifPicker: false
    }
  }

  handleSubmit = (event) => {
    event.preventDefault()
    event.target.reset();
    const data = this.state
    //data.title if you want single item, this will help when sending req to db
    console.log("Final Output is: ", data)

    fetch('/posts/add', { 
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify ({
          title: data.title,
          postBody: data.postBody,
           giphyUrl: data.giphyUrl,
           approved: 1,
           postPicture: 'myurl.com',
              userId: 1,
              userIdto: 2
        })
      })
      .then(function(response) {
        return response.json()
        console.log(data.postBody)
      }).then(function(body) {
        console.log(body);
      });
  }

  handleInputChange = (event) => {
    console.log(event.target.name)
    console.log(event.target.value)
    this.setState({
      [event.target.name]: event.target.value
    })
  }

  displayGifPicker = () => {
    this.setState({
      displayGifPicker: !this.state.displayGifPicker
    })
}

getGifState = (selectedUrl) => {
  this.setState({ giphyUrl: selectedUrl})
}

getUserTo = (selectedUser) => {
  console.log(selectedUser)
  this.setState({ userIdto : selectedUser});
}

//  getUserTo = (name) => (event) => {
//   console.log(event.target.value)
//   this.setState({ userIdto: event.target.value });

// };

  render () {
    const {title, postBody} = this.state
    const displayGifPicker = this.state.displayGifPicker
    return (
      <Grid item xl={8}>
     {/* <Card className={classes.card} style={mt4}>  */}
     <Card style={mt4}> 
      <CardContent >
          <NameDropDown onChange={this.getUserTo}/> 
          <PostInput onChange={this.handleInputChange} onSubmit={this.handleSubmit}/>
          {displayGifPicker ? (<AddGif selectedGif = {this.getGifState} />) : (<Button size="small" onClick={this.displayGifPicker} ><button>Add Gif</button></Button>)}
        <CardActions>
        {/* <Button size="small">Submit VH5</Button> */}
        </CardActions>
      </CardContent>
    </Card>
  </Grid>
    )
  }
}

export default PostBox;

我想在子组件中选择值后将其发送到 userIdTo 中的父组件的状态。

这是子函数

    export default function NameDropDown({onChange}) {
  const classes = useStyles();
  const [state, setState] = React.useState({
    open: false,
    name: '',
  });

  const handleChange = name => event => {
    setState({ ...state, [name]: event.target.value });
  };

  const handleClickOpen = () => {
    setState({ ...state, open: true });
  };

  const handleClose = () => {
    setState({ ...state, open: false });
  };

  return (
    <div>
      <Button onClick={handleClickOpen}>Select User To Send VH5</Button>
      <Dialog disableBackdropClick disableEscapeKeyDown open={state.open} onClose={handleClose}>
        <DialogTitle>Select a User</DialogTitle>
        <DialogContent>
          <form className={classes.container}>
            <FormControl className={classes.formControl}>
              <InputLabel htmlFor="age-simple">User</InputLabel>
              <Select
                value={state.name}
                onChange={onChange}
                onChange={handleChange('name')}
                input={<Input id="age-simple" />}
              >
                <MenuItem value="">
                  <em>None</em>
                </MenuItem>
                <MenuItem value={'Julio'}>Julio</MenuItem>
                <MenuItem value={'Corey'}>Corey</MenuItem>
                <MenuItem value={'Brenda'}>Brenda</MenuItem>
              </Select>
            </FormControl>
          </form>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} color="primary">
            Cancel
          </Button>
          <Button onClick={handleClose} color="primary">
            Ok
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}

【问题讨论】:

  • NameDropDown 是您的子组件对吗?可以展示一下吗?
  • 是的,没错
  • 你能在 NameDropDown 中显示代码吗?
  • 抱歉刚刚上传了

标签: javascript reactjs react-hooks


【解决方案1】:

好吧,我从中得到的是,首先你在 Select 上有两个 onChange 事件监听器 只需在您的子组件中拥有一个 onChange 作为

<Select
  value={state.name}
  onChange={handleChange('name')}
  input={<Input id="age-simple" />}
 >

比在你的句柄更改调用 onChange 传递到 props 中的值为

const handleChange = name => event => {
 setState({ ...state, [name]: event.target.value });
 onChange(event.target.value)
}

这样你父母的状态就会更新

希望对你有帮助

【讨论】:

  • 啊,我现在明白了,非常感谢。
  • 没问题很高兴为您提供帮助,如果它是正确的解决方案,您可以接受答案,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
  • 2020-11-13
  • 2021-09-29
相关资源
最近更新 更多