过去几个小时,我一直试图将数据库记录立即显示为用户类型的电子邮件地址。似乎渲染属性不显示结果。再次,因为我试图使用 dangerouslySetInnerHTML()显示结果,所以
dataType: 'json'
设置为dataType: 'html'
。它还显示错误未捕获的TypeError:无法读取未定义的属性'email'
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="build/react.min.js"></script>
<script src="build/react-dom.min.js"></script>
<script src="build/browser.min.js"></script>
<script src="build/jquery.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.state = {email: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
componentDidMount() {
$(".search").keyup(function()
{
$.ajax({
url: "search.php",
type: "POST",
//dataType: 'html',
//ContentType: 'application/json',
success: function(data) {
email: this.state.email;
this.setState({data: data});
}.bind(this),
error: function(jqXHR) {
console.log(jqXHR);
}.bind(this)
})
})// end search
}
render() {
return (
<div>
<label>Search by Email:
<input className="search" id="email" name="email" type="text" value={this.state.email} onChange={this.handleChange} />
</label>
{
this.state.data ?
<div dangerouslySetInnerHTML={{__html: this.state.data}} />
: <div>Loading...</div>
}
</div>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
</script>
</body>
</html>
的search.php
<?php
include('db.php');
if($_POST)
{
$gg=strip_tags($_POST['email']);
$q=htmlentities($gg);
//$q=$_POST['searchword'];
$result = $db->prepare("select * from group_data where group_name like :group_name or group_name1 like :group_name1 order by id LIMIT 20");
$result->execute(array(
':group_name' => '%'.$q.'%',
':group_name1' => '%'.$q.'%'
));
while ($row = $result->fetch()) {
$gn=htmlentities($row['group_name'], ENT_QUOTES, "UTF-8");
$gn1=htmlentities($row['group_name1'], ENT_QUOTES, "UTF-8");
?>
<div class="display_box" align="left">
<span style="font-size:9px; color:#999999"><?php echo $gn; ?></span></div>
<?php
}
}
else
{
}
?>
有人可以帮我解决问题。感谢
答案 0 :(得分:0)
您的结果永远不会显示,因为您只是返回标签和输入,从未到达其他回报。
因此,为了让您的代码正常工作,您的渲染应该是这样的:
render() {
return (
<div> //Remember to wrap it in a div, render should only return one root element
<label>Search by Email:
<input className="search" id="email" name="email" type="text" value={this.state.email} onChange={this.handleChange} />
</label>
{
this.state.data ?
<div dangerouslySetInnerHTML={{__html: this.state.data}} />
: <div>Loading...</div>
}
</div>
);
}
您可以查看一个有效的示例here。
修改强>
要修复Uncaught TypeError: Cannot read property 'email' of undefined
,您需要将组件绑定到keyup的回调。
像这样:$(".search").keyup(function() { ... }.bind(this)) // end search