首页 > 解决方案 > ReactJS- Calling a dynamic link based on a prop value

问题描述

i have a cards.js which has the following function. Now the calling method passes three values . header1, header2 and Link (this is the *.js page that has to be called)

export default function Cards(props) {
  const classes = useStyles();
    return (
      <div className="App">
        <Card className={classes.card} variant="outlined">
          <CardContent>
            <Typography
              variant={"h5"}
              gutterBottom
            >
              {props.header1}
            </Typography>
            <Typography
              variant={"caption"} >
             {props.header2}
            </Typography>
            <Divider className={classes.divider} light />


            <Button variant="contained" color="secondary" onClick={()=> (call either link1.js or link2.js )}>
          Lets goooooo!
          </Button>

          </CardContent>
        </Card>
      </div>
    );
  }```



calling method


class UIM extends Component {
  render() {
    return (
      <div className="text-page">
        <Grid container alignItems="center" justify="space-evenly" >
          <Grid ><Cards header1="card 1 for a task1" header2="click  text2" link="link1"/></Grid>
          <Grid ><Cards header1=" card 2 for task 2" header2=" click text 2"  link="link2"/></Grid>
        </Grid>
      </div>
    )
  }

}

I am new to react and learning right now, so wondering if such a thing is possible or should i use router to route to different pages (ie. call either link1.js or link2.js ) ??

标签: javascriptreactjsfunction

解决方案


我通过添加 pathname:props.link 发现我可以让按钮链接到材料 ui 按钮中的多个位置。

 <Card className={classes.card} variant="outlined">
          <CardContent>
            <Typography
              variant={"h5"}
              gutterBottom
            >
              {props.header1}
            </Typography>
            <Typography
              variant={"caption"} >
             {props.header2}
            </Typography>
            <Divider className={classes.divider} light />
            <Button variant="contained" color="secondary">
            <NavLink to={{pathname:props.link}}>Lets goooooo!</NavLink>
          </Button>
          </CardContent>
        </Card>


推荐阅读