Sha*_*Ops 1 javascript reactjs
我想在函数内部声明一个全局变量,然后在函数外部使用它。我尝试将 JSX 放入函数中,以便可以轻松访问它,但这不起作用,因为渲染器返回 null。
应用程序.JS:
class App extends React.Component {
render() {
firebase
.database()
.ref()
.limitToLast(1)
.on('child_added', function (childSnapshot) {
var snap = childSnapshot.val();
var category = snap.category;
var condition = snap.condition;
var postname = snap.postname;
var postprice = snap.postprice;
var username = snap.username;
var usernumber = snap.usernumber;
var imageURL = snap.imageURL;
var postdescription = snap.postdescription;
var whatsapplink = 'https://wa.me/' + usernumber + '?text=';
});
return (
<>
<div></div>
<div style={{float: 'left'}}>
<Ads
imageURL={imageURL}
name={postname}
price={postprice}
category={category}
condition={condition}
description={postdescription}
username={username}
usernumber={usernumber}
whatsapplink={whatsapplink}
/>
</div>
</>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
我应该编写一个函数来在渲染中从 firebase 获取数据吗?
ADS.JS:
import React from 'react';
import '../App.css';
class ads extends React.Component {
render() {
return (
<div>
<img src={this.props.image} alt="image"></img>
<h2>{this.props.name}</h2>
<h2>{this.props.price}</h2>
<h2>{this.props.category}</h2>
<h2>{this.props.condition}</h2>
<h2>{this.props.description}</h2>
<h2>{this.props.username}</h2>
<a href={this.props.whatsapplink}>
<button>Chat with Seller</button>
</a>
</div>
);
}
}
export default ads;
Run Code Online (Sandbox Code Playgroud)
React 组件有一个内置的状态对象。状态对象是存储属于组件的属性值的位置。当状态对象发生变化时,组件会重新渲染。有关 React 生命周期方法的更多信息,请参阅此文档
import React from 'react';
import firebase from 'firebase'
import './App.css'
import Ads from './component/ads.js'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
category: '',
condition: '',
postname: '',
postprice: '',
username: '',
usernumber: '',
imageURL: '',
postdescription: '',
whatsapplink: ''
}
}
componentDidMount() {
firebase.database().ref().limitToLast(1).on('child_added', (childSnapshot) => {
var snap = childSnapshot.val();
this.setState({
category: snap.category,
condition: snap.condition,
postname: snap.postname,
postprice: snap.postprice,
username: snap.username,
usernumber: snap.usernumber,
imageURL: snap.imageURL,
postdescription: snap.postdescription,
whatsapplink: "https://wa.me/" + snap.usernumber + "?text=",
})
})
}
render() {
const { category, condition, postname, postprice, username, usernumber, imageURL, postdescription, whatsapplink } = this.state
return (
<>
<div></div>
<div style={{ float: "left" }}>
<Ads
category={category}
condition={condition}
name={postname}
price={postprice}
username={username}
usernumber={usernumber}
imageURL={imageURL}
description={postdescription}
whatsapplink={whatsapplink} />
</div>
</>
)
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12999 次 |
| 最近记录: |