我希望Button组件在App类中使用Questions组件道具
<?php
require '../includes/DbConnect.php';
$response= array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(isset($_POST['f_name']) and isset($_POST['l_name']) && isset($_POST['pass']) && isset($_POST['email'])){
$f_name=$_POST['f_name'];
$l_name=$_POST['l_name'];
$email=$_POST['email'];
$password=$_POST['pass'];
if(isset($_POST['privacy_level']))
$p_l=$_POST['privacy_level'];
else
$p_l="public";
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$r_s=generateRandomString();
$sql="INSERT INTO users (email,pass,f_name,l_name,privacy_level,random_username)
VALUES ('$email','$password','$f_name','$l_name','$p_l','$r_s')";
if(mysqli_query($project, $sql)){
$response['error']= false;
$response['message']="User registered Successfully";
}
else {
$response['error']= true ;
$response['message']="Failed to Register";
} }
echo json_encode($response); }
?>
}
class Questions extends React.Component {
render() {
return (
<div>
<h1>what is the {this.props.Number1} X {this.props.Number2}</h1>
</div>
)
}
在类应用程序中,它抛出错误:警告:const Button = (props) => {
return (
<div>
<button onClick={props.click}>{props.choice}</button>
</div>
)
属性收到NaN。如果期望如此,请将值转换为字符串。
children
} }
答案 0 :(得分:1)
似乎在App中您没有props.Number1
或props.Number2
。
您必须在渲染之前生成它们:
render() {
function getRandom(max) {
return Math.floor(Math.random() * Math.floor(max));
}
const N1 = getRandom(10)
const N2 = getRandom(10)
return (
<div className="body">
<Questions Number1={N1} Number2={N2} />
<Button click={this.handelClick} choice={N1 * N2} />
</div>
);
}
我还建议避免在渲染中定义getRandom
,因为每次渲染组件时都会重新定义它。在班级上完成。
class App extends React.Component {
constructor(props) {
super()
this.state = {
count: 0,
cicked: false,
number1: this.getRandom(10),
number2: this.getRandom(10)
}
this.handleClick = this.handleClick.bind(this)
}
getRandom = max =>
Math.floor(Math.random() * Math.floor(max))
handleClick() {
this.setState(prevState => ({
count: prevState.count + 1,
clicked: !prevState.clicked,
number1: this.getRandom(10),
number2: this.getRandom(10)
}))
}
render() {
return (
<div className="body">
<Questions
Number1={ this.state.number1 }
Number2={ this.state.number1 }
/>
<Button
click={ this.handleClick }
choice={ this.state.number1 * this.state.number2 }
/>
</div>
);
}
}