[英]How to display value of JSX function in Reactjs
I am quite new to jsx and while making my first Reactjs project today, I am facing this issue where I am unable to display the value of a function in the render method.我对 jsx 很陌生,今天在制作我的第一个 Reactjs 项目时,我面临这个问题,我无法在渲染方法中显示函数的值。
This is my parent page (Homescreen.jsx)这是我的父页面 (Homescreen.jsx)
(I have commented on the sections where I felt that I have gone wrong) (我已经评论了我觉得我出错的部分)
import React, { Component } from 'react';
import Items from './Items'
class Render extends Component {
render() {
return (
<div>
<Items number="This is the first item !" /> {/*This is where I am adding props to Items*/}
<br>
<Items number="This is the second item !" />
</div>
);
}
}
export default Render;
This is the child page (Items.jsx)这是子页面 (Items.jsx)
import React, { Component } from 'react';
class Items extends Component {
// This is where I attempted to get the prop
Items = (props) => {
return (
<p>{props.number}</p>
)
}
render() {
return (
<div className="form-group">
{this.Items} {/*This is where I tried to display the output of "number" prop*/}
</div>
);
}
}
export default Items;
The end result is that the "Items" function has no output and I am getting an output which is the same as the output before adding the "Items" function.最终结果是“Items”函数没有输出,我得到的输出与添加“Items”函数之前的输出相同。
Just use this.props.number
in render method.只需在渲染方法中使用
this.props.number
。 (you can access all props from this.props
). (您可以从
this.props
访问所有道具)。 Try the snippet, there are two ways shown here.试试这个片段,这里显示了两种方法。
class Items extends React.Component { Items2 = (props) => { return ( <p>{props.number}</p> ) } render() { return ( <div className="form-group"> {this.props.number} {/* alternatively */} {this.Items2(this.props)} </div> ); } } class Render extends React.Component { render() { return ( <div> <Items number="This is the first item !" /> <br/> <Items number="This is the second item !" /> </div> ); } } ReactDOM.render(<Render />, document.getElementById("app"))
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <div id="app"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.