So I have a custom component like this:
class MyComponent extends React.Component {
render() {
return (
<TouchableHighlight style={this.props.buttonStyle}>
<Text style={styles.buttonText}>Button</Text>
</TouchableHighlight>
);
}
}
And I use the component like this:
class RootView extends React.Component {
render() {
return (
<View>
<MyComponent/>
<MyComponent/>
</View>
);
}
}
The RootView is resizable. What I want to do is shrinking it's children MyComponent when RootView is small enough. And I need to shrink each MyComponent at a time: when RootView is small enough, shrink the first MyComponent, and when the first MyComponent reach a minimal size, shrink the second MyComponent.
I know there's refs in react-native, but it does not seem to work for custom component.
You can add a ref to a custom component:
<Separator ref='sep' style={styles.offsetSeparator} />
So you should be able to do what you need.
However, when you find yourself having a strong dependency between different components, it means that it's probably a good time to start using Flux or something similar and then hold the data in a Store which will hold all the information needed for all 3 components. More about Flux here: https://facebook.github.io/flux/
Related
I want to change the bottom tab icon from my home screen or another component. I don't know how to achieve it, in Android I can use interface and EventBus but I'm not sure there something equivalent in React-Native, I tried using redux store but didn't work for me I have 5 buttons in the bottom tab bar I want to change the the centre button when I have some check fulfilled from the backend in my home screen.How can I change it from the home screen? any help will be appriciated thank you in advance
You can use ref to access method of other component.
https://facebook.github.io/react-native/docs/direct-manipulation
EDIT:
Sorry for the late reply, the ref method works best if both components are siblings.
Here see this code:
class TestPage1 extends Component {
constructor(props) {
super(props)
this.state={}
};
onDoSomething=()=>{
this.comp2_ref.callThisMethod()
}
render() {
return (
<View>
<Comp1 onDoSomething={this.onDoSomething}/>
<Comp2 onRef={(ref)=>{
this.comp2_ref=ref;
})/>
</View>
)
}
}
class Comp1 extends Component{
render(){
return(<View>
<Button onPress={()=>{
typeof
this.props.onDoSomething==='function'&&this.props.onDoSomething()
}}></Button></View>)
}
}
class Comp2 extends Component{
callThisMethod=()=>{
//do something for comp2 that will be called by comp 1
}
render(){
return(<View></View>)
}
componentDidMount(){
typeof this.props.onRef==='function'&&this.props.onRef(this);
}
}
If they are separate then you can also use consumer and provider concept.
I want to change client = {state:0}
You can access it by using this.client.state
I also have a child which contains a button.
I'm trying to change this 'state' variable when you press the button.
For some reason everything I find everything on the internet not working for me.
I've been stuck at it for 5 hours and I think it's time to ask help myself
import React from 'react';
import { StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import Home from './Components/Home';
import Activity from './Components/Activity';
export default class App extends React.Component {
client = {state:0}
render() {
if(this.client.state == 0){
return(
<View style={{flex: 1}}>
<Home />
<Child />
</View>
);
} else {
return(
<View style={{flex: 1}}>
<Activity />
<Child />
</View>
);
}
There are different ways of doing this. It could be done with Redux for example, but let's take a simpler approach.
Also note that it can't be done by props, because a child component cannot update its parents' props.
Also note that the way you are using the state seems rather strange. It should be set on the class level (or component level).
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {myProperty: 0};
}
}
You could pass a callback method to the Child React Component.
<Child callback={this.onButtonClick} />
On the Client Component, create that callback method:
onButtonClick() {
this.setState({buttonClicked: true});
}
To keep it clean, define the initial value in the constructor. You'll also have to bind the function to have a correct this parameter, otherwise the this variable will be from the event instead of the class you're expecting.
constructor(props) {
super(props);
this.state = {buttonClicked: false};
this.onButtonClick = this.onButtonClick.bind(this);
}
That's it for the Client component.
Now on the Child Component, you'll need to trigger this callback method when possible.
Imagine the Child has the following button, add an event handler on the child component as well, onChildButtonClick. You'll also have to bind in the constructor.
constructor(props) {
super(props);
// bind this for access to this class' data
this.onChildButtonClick = this.onChildButtonClick.bind(this);
}
onChildButtonClick() {
// Might want to do a typeof is function check here too
if (this.props.callback) {
// Trigger the callback on the parent component, letting it know the button was triggered
this.props.callback();
}
}
render() {
return <button onClick={this.onChildButtonClick}>Click me</button>;
}
During initialisation, the Parent component sends a callback method to the child component. Whenever the button is clicked on the child component, the child component triggers the function (callback) given by the parent, essentially running a piece of code on the parent component, which then updates the state with the requested value (could be a string, or anything).
Redux
Redux is another way of doing it, which basically keeps a sort of tracked database that can be used from any component, by pageload - however, that would require an entire tutorial.
I have a <view> touching which will open a collapsible view. I have used react-native-collapse-view for it (https://www.npmjs.com/package/react-native-collapse-view) I have <text> on top of <view> which is covering it full. I am setting some conditions in onPress event of the <text> element.
Now what I want is if I touch the <text> (obviously I cannot touch view as text is covering it fully), along with onPress event of the <text> the underlaying <view> should also be touched so that it opens the collapsible view.
In short I want to pass the touch event to the parent view in order to complete all work in one touch. I searched and found some content related to onStartShouldSetResponder and pointerEvents but I couldn't get the complete grip as I am a newbie to react native.
in short you need pass function to children for handling events
import React from "react";
class ChildComponent extends React.PureComponent {
render() {
const {handleChildPress} = this.props;
return <Text onPress={handleChildPress}/>;
}
}
class ContainerComponent extends React.PureComponent {
// you need pass this func to children
// =()=> means bind it
handleChildPress=()=>{
console.log('child pressed')
}
render() {
return <ChildComponent handleChildPress={this.handleChildPress}/>;
}
}
export default ContainerComponent
I'm trying to create a small app, but have many questions)
I have 3 screen and use react-navigation to pass data. the scheme is following:
1) loading screen (fetch data and save it to AsyncStorage+handling data and save to obj1 for pickers)
(pass obj1)
2)main screen (get data,render pickers based on it, take selected values and pass them next)
(pass pickers selection+input)
3)some results(get data from Asyncstorage, some calculating and render results)
so I have two questions.
when I navigate back from 3) to 2) I have an error that screen2 need data, which was passed from screen1. yes - i've checked if this data pass to 3 and then to 2 when Back Button is pressed, and there is no error, but I'm sure this is bad solution
and second..trying to explain) on screen 3 some calculations made on pickers selection, so it hasn't problem. but rest of them needed get data from AsyncStorage and then convert it according to Picker values and render to ListView. Despite I'm putting getting from AS on componentWillMount it's still take much time so data for rendering is undefined. Of course I'm using states, but I think this is a bad logic of data handling..
UPD
so I'm trying pass data from child(screen) to parent(index.ios.js), where it define as first loading view( I'm using navigator's stack screens)
export default class App extends Component {
constructor(props) {
super(props);
};
}
myCallback(dataFromChild) {
console.log("yeah", dataFromChild);
}
render() {
return (
<LoadingScreen callbackFromParent={this.myCallback}/>
);
}
}
and LoadingScreen.js:
render() {
return(
<View style={{flex: 1, backgroundColor: '#dc143c', marginTop:20}}>
<Image
source={require('./WhiteLogo.png')}
style={{flex:3, height: undefined, width: undefined, marginLeft:20, marginRight:20}}
resizeMode="contain"
qwer={this.props.callbackFromParent('listInfo').bind(this)}
/>
<Spinner color='white' style={{flex:1}}/>
</View>
);
}
}
and I've got an error "Unhandled JS Exception: this.props.callbackFromParent is not a function"
AsyncStorage might not be the best solution for what you are trying. Using react-navigation for data delivery is not the best neither. I would suggest checking redux for storing states globally and delivering it to the pages when needed. There is also another way which is passing functions to the props of child components for pulling up any data from child to parent components. You can check this and this or the sample code is below.
Parent
class Parent extends Component {
updateState (data) {
this.setState(data);
}
render() {
<View>
<Child updateParentState={this.updateState.bind(this)} />
</View>
}
}
Child
class Child extends Component {
render() {
<View>
<Button title="Change" onPress={() => {this.props.updateParentState({name: 'test})}} />
</View>
}
}
I am inserting a rightButton into react-native-router-flux using the renderRightButton api. The problem I ran into is that the rightButton needs to access a method within the component.
class App extends React.Component {
render() {
return(
<Router>
<Scene
key="firstScene"
component={FirstScene}
title="First scene"
rightTitle="Apply"
renderRightButton={this.getRightButton}
/>
</Router>
)
}
getRightButton() {
return(
// someMethodOnFirstSceneComponent lives on the FirstScene component
<View onPress{this.someMethodOnFirstSceneComponent}>
<Text>
Invoke Function from Scene Component
</Text>
</View>
)
}
};
One option would be to put all of the data currently in the state of FirstScene into a redux reducer and then put the someMethodOnFirstSceneComponent on the FirstScene component. However, I am trying to keep state within components and not rely on reducers because from my experience, it keeps things easier to reason about.
I've found a way to do that. Not a very nice solution, but it works. I'm setting onRight method in the component constructor
constructor(props) {
super(props);
this.props.component.onRight = () => {
console.warn("call from my onRight function")}
}
}