将React组件作为prop传递给另一个组件

时间:2019-10-16 10:17:53

标签: javascript reactjs

我试图将完整的父组件作为道具传递给它的子组件。而在尝试将某些数据从父级传递到父级时,我将孩子导入了父级。那么,我现在该如何以其他方式做到这一点呢?有什么建议么?正如我想在子组件的某些状态更改时重新呈现Parent组件。 添加示例:

int a, b;
a = int.Parse(Console.ReadLine());
var result = new List<int>();
for (b = 1; b <= a; b++)
{
    if (a % b == 0)
    {
        result.Add(b);
    }
}

Console.Write(string.Join(" and ", result));

1 个答案:

答案 0 :(得分:0)

当您要在父组件和子组件之间切换时,建议将回调函数从父组件传递到子组件,然后访问该函数以导航回父组件。

您的父组件应该是这个

package zapSeleniumIntegration;

import java.lang.reflect.Proxy;    
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class BrowserDriverFactory {

    static WebDriver driver;
    public static WebDriver createChromeDriver(Proxy proxy, String path) {
    // Set proxy in the chrome browser
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();//Getting error as method chrome undefined
            capabilities.setCapability("127.0.0.1", 8080);
            // Set system property for chrome driver with the path
            System.setProperty("webdriver.chrome.driver", "C:\\Users\\kotla.naveen\\Desktop\\chromedriver.exe");
            capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
            ChromeOptions options = new ChromeOptions();
            options.merge(capabilities);
            return new ChromeDriver(options); 
    }
}

您的子组件应该是这个

class A extends React.Component{
  constructor(props, context){
    super(props, context);
    this.state = {
      showB: false
    }
  }

  onClick = () =>{
    this.setState({ 
      showB: !this.state.showB    //This will negate the existing state
    });
  }

  render(){
    return(
      <>  //use Fragments / div here 
      {
        this.state.showB ? 
        <B click={this.onClick}/> //Provide callabck function here
        : 
        <div>
          <button onClick={this.onClick}>VIEW B </button>
          <h1>Some text</h1>
        </div>
      }
      </>
    )
  }
}

Demo

相关问题