Вы должны сохранить это значение в родительском компоненте state
и передать его как реквизит для ребенка.
Когда ваш onClick
уволен, вы должны обновить родителей state
, поэтому обновленный props
будет передан ребенку.
Вот код:
Tournament.js
import React, { Component } from "react";
import Template from './template';
const API = 'http://localhost:8080/api/tournaments';
class Tournaments extends Component {
constructor() {
super();
this.state = {
data: [],
targetId: null,
}
}
componentDidMount() {
fetch(API)
.then((Response) => Response.json())
.then((findresponse) => {
console.log(findresponse)
this.setState({
data:findresponse,
})
})
}
reply_click = id => {
return () => {
this.setState({ targetId: id })
}
}
render() {
return(
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron text-center">
{
this.state.data.map((dynamicData, key) =>
<div>
<a href={"/#/template"} onClick={this.reply_click(dynamicData.id)}>{dynamicData.name}</a>
<a href={"/#/addTeams"}><button type="button" class="btn-lisa">Edit</button></a>
<Template name={dynamicData.id} targetId={this.state.targetId}></Template>
</div>
)
}
</div>
</div>
</div>
</div>
)
}
}
export default Tournaments;
Template.js
import React, { Component } from "react";
import Parser from 'html-react-parser';
import Tournaments from "./Tournaments";
import './template.css';
import './index.css';
const tournyAPI = 'http://localhost:8080/api/tournaments';
const teamAPI = 'http://localhost:8080/api/teams'
class template extends Component {
constructor() {
super();
this.state = {
data: [],
}
}
componentDidMount() {
fetch(tournyAPI)
.then((Response) => Response.json())
.then((findresponse) => {
this.setState({
tournydata: findresponse.filter(res => res.id === this.props.targetId),
})
})
Но сделайте это, используя componentDidUpdate
вместо componentDidMount
, если хотите обновлять свой Template компонент после каждого изменения targetId
.
Вот так:
Template.js
componentDidUpdate(prevProps) {
if (prevProps.targetId !== this.props.targetId) {
fetch(tournyAPI)
.then((Response) => Response.json())
.then((findresponse) => {
this.setState({
tournydata:findresponse.filter(res => res.id === this.props.targetId),
})
})
}
}
Если вам нужно сделать это сразу во время первого рендеринга, просто добавьте проверку, если targetId
не null
в вашем Tournament
компоненте.
Примерно так:
Tournament.js
render() {
...
{this.state.targetId ? <Template name={dynamicData.id} targetId={this.state.targetId}></Template> : null }
...
}