Как получить свойства элемента в React Native для события Click
Как получить доступ к свойствам элемента, не используя ключевое слово this в React Native? У меня есть функция, с которой сам родительский класс связан как "this", но я хочу получить доступ к свойствам элемента, по которому щелкают. Вот код
import {Circle} from 'react-native-svg';
export default App extends Component {
constructor(props) {
super(props);
this.state = {activeX: null}
}
handleTouch(event) {
const x = event.target.cx; //How to access "cx" property here?
this.setState({ activeX: x });
}
render() {
return (
<Circle cx='10' cy='10' r='5' onPress={this.handleTouch.bind(this)}/>
<Circle cx='20' cy='20' r='5' onPress={this.handleTouch.bind(this)}/>
);
}
}
4 ответа
import ReactNativeComponentTree from'react-native/Libraries/Renderer/src/renderers/native/ReactNativeComponentTree';
И доступ к свойствам как
const x = ReactNativeComponentTree.getInstanceFromNode(event.currentTarget)._currentElement.props.cx;
На самом деле лучший способ получить доступ к свойствам компонента в событии - создать компонент и передать ему необходимые данные:
import { Circle } from 'react-native-svg';
class TouchableCircle extends React.PureComponent {
constructor(props) {
super(props);
this.circlePressed = this.circlePressed.bind(this);
}
circlePressed(){
this.props.onPress(this.props.cx);
}
render() {
return (
<Circle cx={this.props.cx} cy={this.props.cy} r={this.props.r} onPress={this.circlePressed}/>
);
}
}
export default App extends Component {
constructor(props) {
super(props);
this.state = {activeX: null}
this.handleTouch = this.handleTouch.bind(this);
}
handleTouch(cx) {
this.setState({ activeX: cx });
}
render() {
return (
<TouchableCircle cx='10' cy='10' r='5' onPress={this.handleTouch}/>
<TouchableCircle cx='20' cy='20' r='5' onPress={this.handleTouch}/>
);
}
}
NB. Совет по производительности от Facebook для обработчиков событий:
Мы обычно рекомендуем связывание в конструкторе или использование синтаксиса инициализатора свойства, чтобы избежать такого рода проблем с производительностью. (т.е. чтобы избежать создания обратного вызова каждый раз, когда компонент выполняет рендеринг)
Извините за оставленный ответ, но я не могу оставить комментарий, так как <50 респ.
Вы должны отредактировать улучшенную часть своего ответа следующим битом:
import ReactNativeComponentTree from 'react-native';
вместо того, что у вас есть сейчас,
import ReactNativeComponentTree from'react-native/Libraries/Renderer/src/renderers/native/ReactNativeComponentTree';
т.к. выдает ошибку (пытается импортировать неизвестный модуль).
Попробуй это
import {Circle} from 'react-native-svg';
export default App extends Component {
constructor(props) {
super(props);
this.state = {
activeX: null,
cx: 10
}
}
handleTouch = () => {
const x = this.state.cx
this.setState({ activeX: x });
}
render() {
return (
<Circle cx={this.state.cx} cy='10' r='5' onPress={this.handleTouch}/>
);
}
}
Вы можете изменить обработчик событий на каррированную функцию, например:
import {Circle} from 'react-native-svg';
export default App extends Component {
constructor(props) {
super(props);
this.state = {activeX: null}
}
//Use ES6 arrow and avoid this.bind
//Curried function handleTouch accepts cx, cy as extra parameters
handleTouch = (cx, cy) => event => {
console.log(cx, cy) // This is how you access props passed to Circle here
console.log(event)
this.setState({ activeX: cx });
}
render() {
//You are actually invoking the handleTouch function here, whose return value is
//a function, which is set as the onPress event handler for the <Circle> component
return (
<Circle cx='10' cy='10' r='5' onPress={this.handleTouch(10, 10)}/>
<Circle cx='20' cy='20' r='5' onPress={this.handleTouch.(20, 20)}/>
);
}
}
Ознакомьтесь с рабочей закуской ниже:
https://snack.expo.io/@prashand/accessing-props-from-react-native-touch-event