reactjs - 使用不同的 props 重用多个 react 组件实例

标签 reactjs reusability react-props react-component

所以我有一个子组件,我想在父容器组件中呈现多个实例。将不同的 Prop 传递给每个 Prop ,以便它们以不同的方式显示。

正在发生的事情是它们都被渲染,脚本中 Prop 的最后一个实例被读入两个实例。因此,下面的两个组件都以 placeHolder==='Describe yourself' 结尾
有没有办法解决这个问题,以便他们每个人都将被专门注入(inject)他们的 Prop ?

           <ButtonMode 
              open={this.state.open}
              handleClose={this.handleClose}
              buttonName='Update'
              modalOpen={this.modalOpen}    
              placeHolder="New picture url"
              change={this.handlePicture}
              label='URL'
            />

           <ButtonMode 
              open={this.state.open}
              handleClose={this.handleClose}
              buttonName='Update'
              modalOpen={this.modalOpen}     
              placeHolder='Describe yourself'
              label='Bio'
              change={this.handleBio}
                />

ButtonMode


class ButtonMode extends Component {
    constructor(props){
        super(props)
        this.state = {
            input:''
        }
        this.handleInput = this.handleInput.bind(this);
        this.handle = this.handle.bind(this);
    }

    handleInput(val){
        this.setState({input:val})
    };

    handle() {

        this.props.change(this.state.input);
    };

    render(){
        const { classes } = this.props;
        return (
            <div>
                <Button 
                    className={classes.button}
                    onClick={this.props.modalOpen}
                    >Update
                </Button>
                <Modal
                    aria-labelledby="simple-modal-title"
                    aria-describedby="simple-modal-description"
                    open={this.props.open}
                    onClose={this.props.handleClose}
                    >
                    <div className={classes.paper}>
                        <TextField
                            id="filled-textarea"
                            label={this.props.label}
                            placeholder={this.props.placeHolder}
                            multiline
                            className={classes.textField}
                            onChange={(e)=>{this.handleInput(e.target.value)}}
                            rows= '4'
                            />
                        <Button 
                            onClick={this.handle}
                            className={classes.button} 
                            color="secondary">Submit</Button>                  
                  </div>
                </Modal>
            </div>
        )
    }
}

Then I used it like that


 class UserCard extends Component {
    constructor(props){
        super(props);
        this.state = {
          tempPro:'',
          open: false,
          profilePicture:''
        }
        this.modalOpen = this.modalOpen.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.handlePicture = this.handlePicture.bind(this);
      }



    // componentDidMount(){
    //   const {userId, profilePic} = this.props;
    //   this.setState({profilePicture:profilePic});
    //   // axios.get(`/api/profile/${userId}`).then(res=>{

    //   //   let {profilePic} = res.data[0];
    //   //   this.setState({profilePic})
    //   // })
    // }


    handlePicture(val){
      this.props.changePic(val);
      this.setState({open:false});
    };

    handleBio(val){

      this.setState({open:false});
    };

    handleClose(){
        this.setState({open: false});
    };
    modalOpen(){
      this.setState({open:true});
    };

    render() {
      const { classes } = this.props;
      const {stories} = this.props;
      let storyShow = stories.map((story,id) => {
        return(
          <div value={story.story_id}>
              <h3>{story.title}</h3>
              <ul className={classes.background}>
                <li>{story.description}</li>
                <li>{story.is_complete}</li>
              </ul>  
          </div>
        )
      });

      return (  
      <div className={classes.rootD}>
        <Grid container>
          <Grid className={classes.itemFix} >
          <Card className={classes.card}>
           <CardMedia
            className={classes.media}
            image={this.props.proPic}
            title={this.props.userName}
            />
            <div>
            <ButtonMode 
                  open={this.state.open}
                  handleClose={this.handleClose}
                  modalOpen={this.modalOpen}    
                  placeHolder="New picture url"
                  change={this.handlePicture}
                  label='URL'
                />
            </div>       
          <CardHeader
            className={classes.titles}
            title={this.props.userName}
            subheader="Somewhere"
            />
            <CardHeader className={classes.titles} title='Bio' />
              <CardContent className={classes.background}>
                <Typography className={classes.bio} paragraph>
                  {this.props.bio}
                </Typography>
              </CardContent> 
              <div>
                <ButtonMode 
                  open={this.state.open}
                  handleClose={this.handleClose}
                  modalOpen={this.modalOpen}     
                  placeHolder='Describe you how you want'
                  label='Bio'
                  change={this.handleBio}
                    />
              </div>
          </Card>
          </Grid>
          <Grid className={classes.itemFixT}>
            <Card className={classes.card}>
            <CardContent>
                <CardHeader 
                  className={classes.titles}
                  title='Works'/>
                <Typography paragraph>
                  <ul>
                    {storyShow}
                  </ul>
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          </Grid>
      </div>
      );
    }
  }

  UserCard.propTypes = {
    classes: PropTypes.object.isRequired,
  };
  function mapStateToProps(state){
    const {userId, profilePic} = state;
    return {
      userId,
      profilePic      
    }
  }

  export default connect(mapStateToProps,{})(withStyles(styles)(UserCard));

最佳答案

我有一个类似的问题,我试图将不同的函数传递给子组件。我有一个 UploadFile 组件,其中包含 <input/><Button/>来自material-ui,我想在整个页面中多次重用这个组件,因为用户有多个文件要上传,为了保存文件,我需要在主页中使用回调函数。
我必须做的是给每个子组件<UploadFile/>在我的情况下,<ButtonMode/>在你的情况下,一个 唯一 ID 作为 Prop 传入,否则,顶级页面无法将每个对子组件的引用与其他任何引用区分开来。
子组件的代码:

function UploadFile({ value, handleFile }) {
const classes = useStyles();

return (
<>
  <input
    accept=".tsv,.fa,.fasta"
    className={classes.input}
    id={value}
    type="file"
    style={{ display: 'none' }}
    onChange={e => handleFile(e.target.files[0])}
  />
  <label htmlFor={value}>
    <Button
      variant="contained"
      color='default'
      component="span"
      startIcon={<CloudUploadIcon />}
      className={classes.button}>
      Upload
    </Button>
  </label>
</>
);
}
这个组件在父组件中的用法(handleFile是我传入的函数,上面定义在父组件中):
<UploadFile value='prosite' handleFile={handlePrositeFile} />
<UploadFile value='pfam' handleFile={handlePfamFile} />

关于reactjs - 使用不同的 props 重用多个 react 组件实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53973294/

相关文章:

c# - 为 ASP.NET 网站编写可重用的 C# 代码

reactjs - 如何使用 TypeScript 以类型安全的方式访问 React 子元素 Prop ?

javascript - 传递给 React 函数后参数未定义?

当背景动态变化时,CSS background-clip 属性未在 React 中应用

javascript - 如何在 React jsx 渲染函数中的每个子元素后面添加一个元素?

javascript - 如何在 React Native 中更改数组键名称

javascript - 如何使通过 useState 钩子(Hook)改变状态的函数可重用?

javascript - 如果 QuestionID 相同,如何更新 setState 中的对象,否则添加到 setState

ios - 更改 textColor、viewBackground 和 subview 背景

javascript - 使用 React 的天气应用程序 : problems inputing custom Lat/Long into API request