我有一个问题,我不知道如何解决。
我试图拨打onClick
内的Component
。但得到了这个错误:
未捕获错误:预期
onClick
侦听器是一个函数,而是获得object
类型的值。
我的代码调用Component
:
import React from 'react';
import './Square.css';
import Controller from './controller.js';
class Square extends React.Component {
render() {
return (
<div className="square" onClick={<Controller/>}>
{this.props.children(<Controller/>)}
</div>
)
}
}
export default Square;
&#13;
我的component
用函数调用:
import React from 'react';
class Controller extends React.Component {
changePlayer = () => {
alert('oi')
}
render(){
return(
<div>
{this.props.position}
</div>
)
}
}
export default Controller;
&#13;
该行,我想传递render
的{{1}}来渲染..
Controller
但它给出了错误。有人帮帮我吗?。
答案 0 :(得分:1)
如果你想从你的父组件中调用子组件的功能,你需要在React中使用ref,你在这里是如何做的:
import UIKit
class ViewController: UIViewController {
var currentValue = 0
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var targetLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var roundLabel: UILabel!
var targetVal = 0
var score = 0
var round = 1
override func viewDidLoad() {
super.viewDidLoad()
currentValue = lroundf(slider.value)
startRound()
}
@IBAction func sliderMoved(_ slider: UISlider){
print("The value is now: \(slider.value)")
currentValue = lroundf(slider.value)
}
@IBAction func showAlert(){
let diff = abs(targetVal-currentValue)
let points = 100 - diff
score += points
round += 1
let message = "You scored \(points)"
let alert = UIAlertController(title: "Hello, world!", message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "Awesome", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
startRound()
}
func startRound(){
updateLabels()
targetVal = 1 + Int(arc4random_uniform(100))
currentValue = 50
slider.value = Float(currentValue)
}
func updateLabels(){
targetLabel.text = String(targetVal)
scoreLabel.text = String(score)
roundLabel.text = String(round)
}
}
答案 1 :(得分:0)
您可以通过将道具传递给由onMouseDown
切换到onMouseUp
并由import React, { Component } from 'react';
import './square.css';
import Controller from './Controller';
class Square extends Component {
state = { clicked: false };
toggleClicked = (clicked = false) => {
this.setState({ clicked });
}
render() {
return (
<div className="square" onMouseDown={this.toggleClicked.bind(this, true)} onMouseUp={this.toggleClicked}>
<Controller clicked={this.state.clicked} />
</div>
)
}
}
export default Square;
关闭的孩子来实现此目的:
<强> Square.jsx 强>
import React, { Component } from 'react';
import './controller.css';
class Controller extends Component {
changePlayer = () => {
alert('oi')
}
componentDidUpdate(prevProps) {
if (this.props.clicked && !prevProps.clicked) {
this.changePlayer();
}
}
render() {
return (
<div className='controller'>
{this.props.position}
</div>
)
}
}
export default Controller
<强> Controller.jsx 强>
if a > 0 and b > 0: # (a,b) = (1,1)
a = a + 1 # a = 2
b = b - 1 # b = 0
if a > 0 or b < 0:
b = b - 1 # -1