如何将状态从子挂钩发送到父状态

时间:2019-10-03 17:44:20

标签: javascript reactjs react-hooks

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

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

  displayGifPicker: false
}

上面是状态,我想输入下拉列表中的UserIdto输入值

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

该方法作为道具传递给componenet

<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>
  );
}

1 个答案:

答案 0 :(得分:0)

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

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

比句柄更改内的onChange传递给prop的值为

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

这样您的父母的状态将被更新

希望有帮助