我无法更改导入的RN件的状态。
我尝试:
this.setState({myState: "This does not do anything"})
但是它不起作用。我怀疑问题出在这里-仅引用主文档。但是我不知道如何改变它。
有趣的是
state = {myState: 'Now it is changed'}
this.setState({})
这有效。但是根据我在这里阅读的内容,不建议这样做。
谢谢!
// MAIN FILE
import React, {Component} from 'react';
import {Button, View } from 'react-native';
import { TestImport } from './TestImport';
type Props = {};
export default class App extends Component<Props> {
_onPressChange = () => {
state = {myState: 'Now it is changed'}
this.setState({})
// the above commented piece works - strangely enough
this.setState({myState: "This does not do anything"})
// this does not work
}
constructor (props) {
super(props)
this.state = {
myState: 'to this'
}
}
render() {
return (
<View>
<View>
<TestImport></TestImport>
</View>
<View>
<Button title="Click to change" onPress={() => this._onPressChange()}/>
</View>
</View>
);
}
}
// IMPORTED FILE
import React from 'react';
import {View, Text, StyleSheet } from 'react-native';
this.state = {
myState: 'Change this'
}
const TestImport = (props) => {
return (
<View>
<Text>{this.state.myState} </Text>
</View>
)
}
export { TestImport };
答案 0 :(得分:0)
流量不是那样的。您的TestImport
即导入的组件应从道具中读取。
// IMPORTED FILE
import React from 'react';
import {View, Text, StyleSheet } from 'react-native';
const TestImport = (props) => {
return (
<View>
<Text>{props.title} </Text>
</View>
)
}
export { TestImport };
并从您的主要组件传递它
<TestImport title={this.state.myState}></TestImport>
因此,当您单击按钮时,它将重新渲染包括您的TestImport
的整个组件,并将通过道具名称myState
传递title
的最新状态值
答案 1 :(得分:0)
从'react'导入React,{组件}; 从'react-native'导入{Button,View}; 从“ ./TestImport”导入TestImport;
导出默认类App扩展组件{
constructor(props) {
super(props)
this.state = {
myState: 'to this'
}
}
_onPressChange = () => {
this.setState({ myState: 'hello everyone do this' })
}
render() {
// console.log(this.state,'love')
return (
<View style={{ justifyContent: 'center', flex: 1, alignItems: 'center' }}>
<View>
<TestImport name={this.state.myState} />
</View>
<View>
<Button title="Click to change" onPress={() => this._onPressChange()} />
</View>
</View>
);
}
}
// app.js
从'react'导入React; 从'react-native'导入{View,Text,StyleSheet};
this.state = { myState:“更改此” }
const TestImport =(props)=> { console.log(props.name,'props') 返回( {props.name}
)
}
导出默认的TestImport; // importtest.js
答案 2 :(得分:0)
如果有用例,则需要使用state
而不是像@Ravi's answer那样使用props
,可以这样做(免责声明:您仍然需要props:D)
class TestImport extends React.Component {
state = {
myState: 'Change this'
}
componentDidUpdate(prevProps) {
const {changedState} = this.props;
if(changedState && changedState !== prevProps.changedState)
this.setState({myState: changedState})
}
...
}
和您的父母
<TestImport changedState={this.state.myState} />