使用 ReactJs 从父元素到子元素获取点击 ID
Get clicked ID from parent to child element with ReactJs
我正在用 ReactJs 开发应用程序,现在我需要将点击的 ID 从 Main.js 页面传递到 Sofa.js ,这将根据您刚刚点击的 ID 显示不同的信息。
我将我的 ming 全部格式化为 PHP,我希望 ReactJs 有一个像 $_GET 这样的全局变量啊哈。也许是,我只是现在不知道。我一直在寻找,但没有找到我要找的东西。我将在下面显示代码。
Main.js 不包含导入的代码:
export class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
token: {},
isLoaded: false,
models: [],
offset: offset,
limit: limit
};
}
componentDidMount() {
/* Some code not relevant to the question, for getting API token */
fetch('url/couch-model?offset=' + offset + '&limit=' + limit, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
models: json.results,
isLoaded: true
}, () => { });
})
}
render() {
const { isLoaded, models } = this.state;
if (!isLoaded) {
return (
<div id="LoadText">
Loading...
</div>
)
} else {
return (
<div>
{models.map(model =>
<a href={"/sofa?id=" + model.id} key={model.id}>
<div className="Parcelas">
<img src={"url" + model.image} className="ParcImage" alt="sofa" />
<h1>{model.name}</h1>
<p className="Features">{model.brand.name}</p>
<button className="Botao">
<p className="MostraDepois">Ver Detalhes</p>
<span>+</span>
</button>
<img src="../../img/points.svg" className="Decoration" alt="points" />
</div>
</a>
)}
<PageButtons offset={offset} />
</div>
)
}
}
}
如您所见,第二个 return 中的 <a>
发送了一个 ID,尽管我不确定这是正确的方法。我试过写 route-js 这样的路径 /sofa/:id
,但不知何故,/sofa/1 中的 CSS 停止工作,无论 ID 是什么。
现在 Sofa.js 代码,没有导入,只有相关代码:
export class Sofa extends React.Component {
constructor(props) {
super(props);
this.state = {
token: {},
isLoaded: false,
model: {}
};
}
componentDidMount() {
fetch(url + '/couch-model/1{/*this show be id clicked and sent by url*/}/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
model: json,
isLoaded: true
}, () => {});
})
}
render() {
const { model, isLoaded } = this.state;
if (!isLoaded) {
return (
<div id="LoadText">
Estamos a preparar o seu sofá!
</div>
)
} else {
return (
<div id="Esquerda">
<h2>{model.area_set.map(area => area.name)}</h2>
<h1>{model.name}</h1>
<p>Highly durable full-grain leather which is soft and has a natural look and feel.</p>
<h3>Design</h3>
<h4>Hexagon</h4>
</div>
);
}
}
}
还有,这里是route.js:
const Routes = (props) => (
<BrowserRouter>
<Switch>
<Route path='/sofa/:id' component={Sofa}/>
<Route path='/home' component={Home}/>
<Route path='*' component={NotFound}/>
</Switch>
</BrowserRouter>
);
export default Routes;
我看到你没有使用(从我从示例中看到的)react-router。
我真的推荐你使用它,因为它让这种情况变得非常简单。
如this示例
const ParamsExample = () => (
<Router>
<div>
<h2>Accounts</h2>
<ul>
<li>
<Link to="/netflix">Netflix</Link>
</li>
<li>
<Link to="/zillow-group">Zillow Group</Link>
</li>
<li>
<Link to="/yahoo">Yahoo</Link>
</li>
<li>
<Link to="/modus-create">Modus Create</Link>
</li>
</ul>
<Route path="/:id" component={Child} />
</div>
</Router>
);
并且 Child 组件已匹配路由注入。
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
);
Here is a CodeSandbox that you can play around with
在您的例子中,Sofa 是 Child 组件。您可以使用从 url 收到的 ID 在 componentDidMount 上调用您想要的任何 API。
我正在用 ReactJs 开发应用程序,现在我需要将点击的 ID 从 Main.js 页面传递到 Sofa.js ,这将根据您刚刚点击的 ID 显示不同的信息。
我将我的 ming 全部格式化为 PHP,我希望 ReactJs 有一个像 $_GET 这样的全局变量啊哈。也许是,我只是现在不知道。我一直在寻找,但没有找到我要找的东西。我将在下面显示代码。
Main.js 不包含导入的代码:
export class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
token: {},
isLoaded: false,
models: [],
offset: offset,
limit: limit
};
}
componentDidMount() {
/* Some code not relevant to the question, for getting API token */
fetch('url/couch-model?offset=' + offset + '&limit=' + limit, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
models: json.results,
isLoaded: true
}, () => { });
})
}
render() {
const { isLoaded, models } = this.state;
if (!isLoaded) {
return (
<div id="LoadText">
Loading...
</div>
)
} else {
return (
<div>
{models.map(model =>
<a href={"/sofa?id=" + model.id} key={model.id}>
<div className="Parcelas">
<img src={"url" + model.image} className="ParcImage" alt="sofa" />
<h1>{model.name}</h1>
<p className="Features">{model.brand.name}</p>
<button className="Botao">
<p className="MostraDepois">Ver Detalhes</p>
<span>+</span>
</button>
<img src="../../img/points.svg" className="Decoration" alt="points" />
</div>
</a>
)}
<PageButtons offset={offset} />
</div>
)
}
}
}
如您所见,第二个 return 中的 <a>
发送了一个 ID,尽管我不确定这是正确的方法。我试过写 route-js 这样的路径 /sofa/:id
,但不知何故,/sofa/1 中的 CSS 停止工作,无论 ID 是什么。
现在 Sofa.js 代码,没有导入,只有相关代码:
export class Sofa extends React.Component {
constructor(props) {
super(props);
this.state = {
token: {},
isLoaded: false,
model: {}
};
}
componentDidMount() {
fetch(url + '/couch-model/1{/*this show be id clicked and sent by url*/}/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
}
}).then(res => {
if (res.ok) {
return res.json();
} else {
throw Error(res.statusText);
}
}).then(json => {
this.setState({
model: json,
isLoaded: true
}, () => {});
})
}
render() {
const { model, isLoaded } = this.state;
if (!isLoaded) {
return (
<div id="LoadText">
Estamos a preparar o seu sofá!
</div>
)
} else {
return (
<div id="Esquerda">
<h2>{model.area_set.map(area => area.name)}</h2>
<h1>{model.name}</h1>
<p>Highly durable full-grain leather which is soft and has a natural look and feel.</p>
<h3>Design</h3>
<h4>Hexagon</h4>
</div>
);
}
}
}
还有,这里是route.js:
const Routes = (props) => (
<BrowserRouter>
<Switch>
<Route path='/sofa/:id' component={Sofa}/>
<Route path='/home' component={Home}/>
<Route path='*' component={NotFound}/>
</Switch>
</BrowserRouter>
);
export default Routes;
我看到你没有使用(从我从示例中看到的)react-router。
我真的推荐你使用它,因为它让这种情况变得非常简单。
如this示例
const ParamsExample = () => (
<Router>
<div>
<h2>Accounts</h2>
<ul>
<li>
<Link to="/netflix">Netflix</Link>
</li>
<li>
<Link to="/zillow-group">Zillow Group</Link>
</li>
<li>
<Link to="/yahoo">Yahoo</Link>
</li>
<li>
<Link to="/modus-create">Modus Create</Link>
</li>
</ul>
<Route path="/:id" component={Child} />
</div>
</Router>
);
并且 Child 组件已匹配路由注入。
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
);
Here is a CodeSandbox that you can play around with
在您的例子中,Sofa 是 Child 组件。您可以使用从 url 收到的 ID 在 componentDidMount 上调用您想要的任何 API。